Ho questa estensione che creerà un nuovo array che hanno gruppo di matrici a caso dal dato array:errore fatale: scambiando un luogo con se stesso non è supportato con Swift 2.0
extension Array {
var shuffle:[Element] {
var elements = self
for 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]]=[]
for i in 0...(count/n)-1 {
var tempArray:[Element] = []
for index in 0...n-1 {
tempArray.append(self[index+(i*n)])
}
result.append(tempArray)
}
return result
}
}
E io sto usando come questo:
let mainArr = Array(1...60)
let suffeldArr = mainArr.shuffle.groupOf(10)
print(suffeldArr)
E stamperà come:
[[10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60]]
Ma mi sta dando un errore in fase di esecuzione tim e in questa linea:
swap(&elements[index], &elements[ Int(arc4random_uniform(UInt32(elements.count-index)))+index ])
che dice:
fatal error: swapping a location with itself is not supported
Si stava lavorando bene in 1.2, ma ora non sta funzionando in 2.0.
Non so come risolvere questo.
Nota che il codice in http://stackoverflow.com/a/24029847/1187415 è stato aggiornato per risolvere questo problema: http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in -swift/24029847 # comment52863556_24029847 –
Grazie ... @MartinR –