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

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

    Use arc4random_uniform(n) for a random integer between 0 and n-1.

    let diceRoll = Int(arc4random_uniform(6) + 1)
    

    Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty).

提交回复
热议问题