1

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.

edit: This was marked a duplicate to a question already asked but that one appears to be old and for swift 2, and doesn't work for me....thanks though.

Tommy Draughn
  • 179
  • 1
  • 12

1 Answers1

1

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.

adev
  • 2,052
  • 1
  • 21
  • 33