我使用这个扩展方法来生成一个随机数:
func Rand(_ range: Range<UInt32>) -> Int {
return Int(range.lowerBound + arc4random_uniform(range.upperBound - range.lowerBound + 1))
}
我喜欢它 b/c 这不是废话,你只是这样调用它:
let test = Rand(1...5) //generates a random number between 1 and 5
老实说,我不知道为什么 Swift 中的事情需要如此复杂,但我离题了..
所以我现在在 Swift3 中收到一个错误
No '...' candidates produce the expected contextual result type 'Range<UInt32>'
有谁知道这意味着什么,或者我怎样才能让我很棒的 Rand 函数再次运行?我想 x...y 不再创建范围或 x..y 必须明确定义为 UInt32?有什么建议可以让事情变得更简单吗?
非常感谢,感谢您的宝贵时间!
最佳答案
在 Swift 3 中有四种 Range 结构:
-
"x" ..< "y"
⇒Range<T>
-
"x" ... "y"
⇒ClosedRange<T>
-
1 ..< 5
⇒CountableRange<T>
-
1 ... 5
⇒CountableClosedRange<T>
(运算符 ..<
和 ...
被重载,因此如果元素是可跨越的(随机访问迭代器,例如数字和指针),将返回可数范围。但是这些运算符仍然可以返回普通范围以满足类型检查器。)
由于 Range 和 ClosedRange 是不同的结构,您不能将它们相互隐式转换,因此会出错。
如果你想让 Rand 接受 ClosedRange 和 Range,你必须重载它:
// accepts Rand(0 ..< 5)
func Rand(_ range: Range<UInt32>) -> Int {
return Int(range.lowerBound + arc4random_uniform(range.upperBound - range.lowerBound))
}
// accepts Rand(1 ... 5)
func Rand(_ range: ClosedRange<UInt32>) -> Int {
return Int(range.lowerBound + arc4random_uniform(range.upperBound + 1 - range.lowerBound))
}
关于ios - Swift3随机扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371326/