• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Swift的通用随机函数

用户头像
it1352
帮助3

问题说明

我已经研究过并研究了许多不同的随机函数,但它们的缺点是它们只适用于一种数据类型。我想要一个方法有一个函数工作的双,浮动,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.

正确答案

#1

理论上,您可以端口代码,例如这个回答(这不是一个很好的解决方案,取决于你的需要,因为 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
系列文章
更多 icon
同类精品
更多 icon
继续加载