在Swift 1.2中没有正确实现Shuffle功能

时间:2015-07-12 13:31:05

标签: ios arrays swift shuffle swift-playground

我有一个函数,用于混乱数组。这个功能在游乐场工作正常但是当我试图在我的项目上实现它我有一个错误。

以下是代码:

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时,会发生错误。任何人都可以告诉我应该在哪里添加该功能,或者我应该做些什么来正确实现此代码。

1 个答案:

答案 0 :(得分:1)

您必须将var ans2 = ans1.area.bind(ans1); 的调用移至任何方法的主体。例如var ans2 = Rectangle.prototype.area.bind(ans1); 。你要么必须将shuffle的声明和定义移到那里 - 或者至少把它移到类声明的开头:

viewDidLoad