作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的示例代码
import Foundation // ar4random_uniform
extension CollectionType where Self.Index.Distance == Int {
var randomElement: Self.Generator.Element? {
if !isEmpty {
let i = Int(arc4random_uniform(UInt32(count)))
return self[startIndex.advancedBy(i)]
} else {
return nil
}
}
}
let arr = ["alfa", "beta","gama"]
let view = "abcdefghijklmnopqrstuvwxyz".characters
let dict:Dictionary<Int,Any> = [1:"a",2:true,3:1]
let range = Range<Int>(start: -99, end: 100)
let b = UnsafeMutablePointer<Int>.alloc(10)
for i in 0..<10 { (b+i).memory = 1000*i }
let buff = UnsafeMutableBufferPointer<Int>(start: b, count: 10)
for i in 0...10 {
print(arr.randomElement!,
view.randomElement!,
dict.randomElement!,
range.randomElement!,
buff.randomElement!)
}
/*
gama z (1, "a") 62 2000
alfa i (1, "a") 4 9000
alfa f (1, "a") 14 6000
gama g (1, "a") 68 8000
beta a (2, true) 42 7000
alfa y (1, "a") -76 1000
alfa i (1, "a") 76 4000
gama f (2, true) 79 3000
beta s (2, true) 46 3000
beta l (1, "a") -17 9000
gama q (3, 1) 62 9000
*/
代码按预期工作。
问题是,Swift 的哪个内置类型符合 CollectionType 协议(protocol),其中 Self.Index.Distance != Int
以及如何在这种情况下实现相同的行为?
最佳答案
typealias Distance : _SignedIntegerType = Int
因此每个 Index.Distance
都必须符合 _SignedIntegerType
。每个 _SignedIntegerType
都 promise 与 IntMax
(最宽的可用整数)之间的转换:
init(_: IntMax)
func toIntMax() -> IntMax
将这两个事实放在一起,我们可以计算出一个随机索引(最多 231-1 个元素;对于大于此的集合,这将崩溃):
let randomDistance = Index.Distance(arc4random_uniform(UInt32(count.toIntMax())).toIntMax())
let randomIndex = startIndex.advancedBy(randomDistance)
return self[randomIndex]
关于swift2 - 如何从 CollectionType 中获取随机元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34321070/
我是一名优秀的程序员,十分优秀!