栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

随机排列swift 3

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

随机排列swift 3

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

一个解决方案是使用

startIndex
endIndex
代替
0
and
count

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设计指南”,它

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中添加了一个(甚至更通用的)Swift 3版本


对于 Swift 4(Xpre 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)        }    }}

有关的更多信息,请参见SE-0173

MutableCollection.swapAt(_:_:)
swapAt


Swift 4.2 (Xpre 10,当前处于beta版)开始,具有 SE-0202 Random
Unification的实现

shuffle()
并且
shuffled()
是Swift标准库的一部分。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/378914.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号