swift2 - fatal error: swapping a location with itself is not supported with Swift 2.0 -
i have extension create new array have group of arrays randomly given array:
extension array { var shuffle:[element] { var elements = self index in 0..<elements.count { swap(&elements[index], &elements[ int(arc4random_uniform(uint32(elements.count-index)))+index ]) } return elements } func groupof(n:int)-> [[element]] { var result:[[element]]=[] in 0...(count/n)-1 { var temparray:[element] = [] index in 0...n-1 { temparray.append(self[index+(i*n)]) } result.append(temparray) } return result } }
and using this:
let mainarr = array(1...60) let suffeldarr = mainarr.shuffle.groupof(10) print(suffeldarr)
and print like:
[[10 random element between 1 60], [10 random element between 1 60], [10 random element between 1 60], [10 random element between 1 60], [10 random element between 1 60], [10 random element between 1 60]]
but giving me error @ run time @ line:
swap(&elements[index], &elements[ int(arc4random_uniform(uint32(elements.count-index)))+index ])
which says:
fatal error: swapping location not supported
it working fine in 1.2 not working in 2.0.
i don't know how solve this.
you trying swap element itself, need perform check see if not trying swap element same spot in array, so:
extension array { var shuffle:[element] { var elements = self index in 0..<elements.count { let newindex = int(arc4random_uniform(uint32(elements.count-index)))+index if index != newindex { // check if not trying swap element swap(&elements[index], &elements[newindex]) } } return elements } func groupof(n:int)-> [[element]] { var result:[[element]]=[] in 0...(count/n)-1 { var temparray:[element] = [] index in 0...n-1 { temparray.append(self[index+(i*n)]) } result.append(temparray) } return result } }
Comments
Post a Comment