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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcakhhk
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20