• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

swift - 随机播放数组 swift 3

[复制链接]
菜鸟教程小白 发表于 2022-12-11 17:36:33 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

如何将下面的函数转换为 swift 3?当前出现 二元运算符 '..<' 无法应用于 'Int' 和 '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



Best Answer-推荐答案


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

一种解决方案是使用 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])
            }
        }
    }
}

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

注意,根据新的 "Swift API Design Guidelines"shuffle() 是变异 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)
        }
    }
}

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


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

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

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap