【问题标题】:Shuffle function is not being implemented correctly in Swift 1.2Swift 1.2 中未正确实现随机播放功能
【发布时间】:2015-07-12 13:31:04
【问题描述】:

我有一个函数,用于对数组进行洗牌。此功能在操场上运行良好,但是当我尝试在我的项目中实现它时出现错误。

代码如下:

import UIKit
import Darwin

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func shuffle<C: MutableCollectionType where C.Index.Distance == Int>(var list: C) -> C {
        var n = count(list)
        if n == 0 { return list }
        let oneBeforeEnd = advance(list.startIndex, n.predecessor())
        for i in list.startIndex..<oneBeforeEnd {
            let ran = Int(arc4random_uniform(UInt32(n--)))
            let j = advance(i,ran)
            swap(&list[i], &list[j])
        }
        return list
    }

    var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    shuffle(numbers)


}

当我打电话给shuffle()expected declaration 时发生错误。谁能告诉我应该在哪里添加函数或者我应该做些什么来正确实现这段代码。

【问题讨论】:

  • 你需要在某个类中声明函数
  • 其实就是这样。我正在更新代码,但它不起作用
  • 现在您对 shuffle 的调用需要在另一个方法中,例如里面viewDidLoad
  • 完美。如果你想添加回答问题,我可以接受它

标签: ios arrays swift shuffle swift-playground


【解决方案1】:

您必须将shuffle 的调用移动到任何方法的主体。例如viewDidLoad。您要么必须将 numbers 的声明和定义也移到那里 - 或者至少将其移到类声明的开头:

class ViewController: UIViewController {
    var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // either have the var decl here

    override func viewDidLoad() {
        super.viewDidLoad()

        var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // or here
        shuffle(numbers)
    }

    ...

    func shuffle<C: MutableCollectionType where C.Index.Distance == Int>(var list: C) -> C {
        ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多