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

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

    In Swift 4.2 you can generate random numbers by calling the random() method on whatever numeric type you want, providing the range you want to work with. For example, this generates a random number in the range 1 through 9, inclusive on both sides

    let randInt = Int.random(in: 1..<10)
    

    Also with other types

    let randFloat = Float.random(in: 1..<20)
    let randDouble = Double.random(in: 1...30)
    let randCGFloat = CGFloat.random(in: 1...40)
    

提交回复
热议问题