gpt4 book ai didi

swift - 随机排列数组swift 3

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

如何将下面的函数转换为 swift 3 ?目前正在获得 Binary operator '..<' cannot be applied to operands of type 'Int' and 'Self.IndexDistance'错误。

extension MutableCollection where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }

for i in 0..<count - 1 { //error takes place here
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}

引用:https://stackoverflow.com/a/24029847/5222077

最佳答案

count 返回一个 IndexDistance,它是描述的类型两个集合索引之间的距离。 IndexDistance 是必须是 SignedInteger ,但不必是 Int 并且可以不同于 Index 。因此无法创建范围 0..<count - 1

一个解决方案是使用 startIndexendIndex 而不是 0count:

extension MutableCollection where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
// empty and single-element collections don't shuffle
if count < 2 { return }

for i in startIndex ..< endIndex - 1 {
let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i
if i != j {
swap(&self[i], &self[j])
}
}
}
}

另一个优点是这也适用于数组切片(第一个元素的索引不一定为零)。

注意根据新的 "Swift API Design Guidelines"shuffle() 是变异洗牌方法的“正确”名称,和 shuffled() 对于返回数组的非变异对应物:

extension Collection {
/// Return a copy of `self` with its elements shuffled
func shuffled() -> [Iterator.Element] {
var list = Array(self)
list.shuffle()
return list
}
}

更新:(更通用的)Swift 3 版本已添加到 同时为 How do I shuffle an array in Swift?


对于 Swift 4 (Xcode 9) 必须替换对 swap() 的调用通过调用集合的 swapAt() 方法来实现。也不再需要对 Index 类型的限制:

extension MutableCollection {
/// Shuffle the elements of `self` in-place.
mutating func shuffle() {
for i in indices.dropLast() {
let diff = distance(from: i, to: endIndex)
let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
swapAt(i, j)
}
}
}

有关 MutableCollection.swapAt(_:_:) 的更多信息,请参见 SE-0173 Add swapAt


Swift 4.2(Xcode 10,目前处于测试阶段)开始,随着 SE-0202 Random Unification , shuffle()shuffled() 是 Swift 标准库的一部分。

关于swift - 随机排列数组swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843647/

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