我在Shuffle Array Swift 3帖子中查看了类似的问题并尝试了答案中的代码,但我仍然在同一行上得到同样的错误。
let j = Int(arc4random_uniform(UInt32(countArray - i))) + i
上面的行引发了错误:
二元运算符' - '不能应用于'C.IndexDistance'和'Range C.IndexDistance'类型的操作数
整个功能:
//function used to shuffle imageArray
func shuffle<C: MutableCollection>(_ imageArray: C) -> C where C.Index == Int {
var imageArray = imageArray
var countArray = imageArray.count
for i in [1 ..< countArray] {
countArray = imageArray.count
let j = Int(arc4random_uniform(UInt32(countArray - i))) + i
swap(&imageArray[i], &imageArray[j])
}
return imageArray
}
修订后的代码(如下)仍然返回相同的错误:
二元运算符' - '不能应用于'C.IndexDistance'和'Range C.IndexDistance'类型的操作数
//function used to shuffle imageArray
func shuffle<C: MutableCollection>(_ imageArray: C) -> C where C.Index == Int {
var imageArray = imageArray
var countArray = imageArray.count
for i in imageArray.startIndex ..< imageArray.endIndex-1 {
countArray = imageArray.count
let j = Int(arc4random_uniform(UInt32(countArray - i))) + i
swap(&imageArray[i], &imageArray[j])
}
return imageArray
}