Tommy Draughn Tommy Draughn - 3 years ago 107
Swift Question

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

I'm trying to use this function I found here for shuffling an array. Can anyone please tell me what I'm doing wrong here. I'm getting "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)

}


Thanks for any help.

Answer Source

From the error description, you should change your shuffle call as:

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
}

You are trying to shuffle an index with itself and in this case i and j both had same value. Hence the error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download