arrays - Swift - trying to use a shuffle function and get fatal error: swapping a location with itself is not supported -
this question has answer here:
i'm trying use function found here shuffling array. can please tell me i'm doing wrong here. i'm getting "fatal error: swapping location 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 c.index == int { var list = list let count = sourcedays.count in 0..<(count - 1) { let j = int(arc4random_uniform(uint32(count - i))) + swap(&list[i], &list[j]) } return list } @ibaction func go(_ sender: any) { yourdays = shuffle(list: sourcedays) print(yourdays) }
thanks help.
edit: marked duplicate question asked 1 appears old , swift 2, , doesn't work me....thanks though.
from error description, should change shuffle call as:
func shuffle<c: mutablecollection>( list: c) -> c c.index == int { var list = list let count = sourcedays.count in 0..<(count - 1) { let j = int(arc4random_uniform(uint32(count - i))) + if != j { swap(&list[i], &list[j]) } } return list }
you trying shuffle index , in case i
, j
both had same value. hence error.
Comments
Post a Comment