Swift 1.2 中未正确实现随机播放功能

Shuffle function is not being implemented correctly in Swift 1.2

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

代码如下:

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。您也必须将 numbers 的声明和定义也移至那里 - 或者至少将其移至 class 声明的开头:

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 {
        ...
    }
}