Swift - trying to use a shuffle function and get fatal error: swapping a location with itself is not supported

Swift - trying to use a shuffle function and get fatal error: swapping a location with itself is not supported

我正在尝试使用我在此处找到的这个函数来随机排列数组。谁能告诉我我在这里做错了什么。我得到 "fatal error: swapping a location with itself is not supported"

var sourceDays = [1,2,3,4,5,6,7]
var yourDays = [1,2,3,4,5,6,7]

func shuffle<C: MutableCollection>( list: C) -> C where C.Index == Int {
    var list = list
    let count = sourceDays.count
    for i in 0..<(count - 1) {
        let j = Int(arc4random_uniform(UInt32(count - i))) + i
        swap(&list[i], &list[j])
    }
    return list
}

@IBAction func go(_ sender: Any) {

    yourDays = shuffle(list: sourceDays)
    print(yourDays)

}

感谢您的帮助。

编辑: 这被标记为与已经提出的问题重复,但那个问题似乎是旧的并且对于 swift 2,并且对我不起作用....不过谢谢。

根据错误描述,您应该将随机播放更改为:

func shuffle<C: MutableCollection>( list: C) -> C where C.Index == Int {
    var list = list
    let count = sourceDays.count
    for i in 0..<(count - 1) {
        let j = Int(arc4random_uniform(UInt32(count - i))) + i
        if i != j {
            swap(&list[i], &list[j])
        }
    }
    return list
}

您正在尝试将索引与自身打乱顺序,在本例中 ij 都具有相同的值。因此错误。