我有这个扩展,它将创建一个新数组,该数组具有从给定数组中随机组成的数组组:
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 } }
我正在这样使用它:
let mainArr = Array(1...60) let suffeldArr = mainArr.shuffle.groupOf(10) print(suffeldArr)
它会像这样打印:
[[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]]
但这在运行时在此行给我一个错误:
swap(&elements[index], &elements[ Int(arc4random_uniform(UInt32(elements.count-index)))+index ])
其中说:
致命错误:不支持与自身交换位置
它在1.2中工作正常,但现在在2.0中不工作。
我不知道该怎么解决。
您尝试与其自身交换元素,则需要执行检查以查看是否不尝试将元素交换至数组中的同一位置,如下所示:
extension Array { var shuffle:[Element] { var elements = self for index in 0..<elements.count { let newIndex = Int(arc4random_uniform(UInt32(elements.count-index)))+index if index != newIndex { // Check if you are not trying to swap an element with itself swap(&elements[index], &elements[newIndex]) } } 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 } }