How does one generate a random number in Apple's Swift language?

后端 未结 25 2095
有刺的猬
有刺的猬 2020-11-22 09:51

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one\'s own program? Or is t

25条回答
  •  星月不相逢
    2020-11-22 10:28

    @jstn's answer is good, but a bit verbose. Swift is known as a protocol-oriented language, so we can achieve the same result without having to implement boilerplate code for every class in the integer family, by adding a default implementation for the protocol extension.

    public extension ExpressibleByIntegerLiteral {
        public static func arc4random() -> Self {
            var r: Self = 0
            arc4random_buf(&r, MemoryLayout.size)
            return r
        }
    }
    

    Now we can do:

    let i = Int.arc4random()
    let j = UInt32.arc4random()
    

    and all other integer classes are ok.

提交回复
热议问题