gpt4 book ai didi

swift - fatal error : swapping a location with itself is not supported with Swift 2. 0

转载 作者:IT王子 更新时间:2023-10-29 05:42:29 25 4
gpt4 key购买 nike

我有这个扩展,它将创建一个新数组,该数组具有从给定数组中随机生成的数组组:

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
}
}

关于swift - fatal error : swapping a location with itself is not supported with Swift 2. 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com