Swift中的通用随机函数 [英] Generic Random Function in Swift
问题描述
我已经研究过并研究了许多不同的随机函数,但它们的缺点是它们只适用于一种数据类型。我想要一个方法有一个函数工作的双,浮动,Int,CGFloat等。我知道我可以只是转换为不同的数据类型,但我想知道是否有一个方法使用泛型。有人知道一种使用swift做一个通用随机函数的方法。感谢。
I have researched and looked into many different random function, but the downside to them is that they only work for one data type. I want a way to have one function work for a Double, Floats, Int, CGFloat, etc. I know I could just convert it to different data types, but I would like to know if there is a way to have it done using generics. Does someone know a way to make a generic random function using swift. Thanks.
推荐答案
理论上,您可以端口代码,例如这个回答(这不是一个很好的解决方案,取决于你的需要,因为 UInt32.max
相对较小)
In theory you could port code such as this answer (which is not necessarily a great solution, depending on your needs, since UInt32.max
is relatively small)
extension FloatingPointType {
static func rand() -> Self {
let num = Self(arc4random())
let denom = Self(UInt32.max)
// this line won’t compile:
return num / denom
}
}
// then you could do
let d = Double.rand()
let f = Float.rand()
let c = CGFloat.rand()
除了... FloatingPointType
不符合保证 /
, +
等操作符的协议(不像 IntegerType
它符合 _IntegerArithmeticType
)。
Except… FloatingPointType
doesn’t conform to a protocol that guarantees operators like /
, +
etc (unlike IntegerType
which conforms to _IntegerArithmeticType
).
虽然:
protocol FloatingPointArithmeticType: FloatingPointType {
func /(lhs: Self, rhs: Self) -> Self
// etc
}
extension Double: FloatingPointArithmeticType { }
extension Float: FloatingPointArithmeticType { }
extension CGFloat: FloatingPointArithmeticType { }
extension FloatingPointArithmeticType {
static func rand() -> Self {
// same as before
}
}
// so these now work
let d = Double.rand() // etc
但是这可能不像你所希望的那样开箱即用毫无疑问包含了一些关于我的浮点数的微妙的无效假设。)
but this probably isn’t quite as out-of-the-box as you were hoping (and no doubt contains some subtle invalid assumption about floating-point numbers on my part).
对于在整数和 Swift团队在之前的邮件组中提到,缺少跨两种类型的协议是一个有意识的决定,因为为这两种类型编写相同的代码是很少正确的,生成随机数的情况肯定是这样,这需要两种非常不同的方法。
As for something that works across both integers and floats, the Swift team have mentioned on their mail groups before that the lack of protocols spanning both types is a conscious decision since it’s rarely correct to write the same code for both, and that’s certainly the case for generating random numbers, which need two very different approaches.
这篇关于Swift中的通用随机函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!