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

后端 未结 25 2064
有刺的猬
有刺的猬 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:11

    Edit for Swift 4.2

    Starting in Swift 4.2, instead of using the imported C function arc4random_uniform(), you can now use Swift’s own native functions.

    // Generates integers starting with 0 up to, and including, 10
    Int.random(in: 0 ... 10)
    

    You can use random(in:) to get random values for other primitive values as well; such as Int, Double, Float and even Bool.

    Swift versions < 4.2

    This method will generate a random Int value between the given minimum and maximum

    func randomInt(min: Int, max: Int) -> Int {
        return min + Int(arc4random_uniform(UInt32(max - min + 1)))
    }
    

提交回复
热议问题