我有这个扩展,它将创建一个新的数组,其中包含从给定数组中随机组的数组: extension Array { var shuffle:[Element] { var elements = self for index in 0..elements.count { swap(elements[index], elements[ Int(arc4ran
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 ])
哪个说:
fatal error: swapping a location with itself is not supported
它在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 } }