Member-only story
How does one generate a random number in Apple’s Swift language?
1 min readOct 6, 2020
Use the standard library functions for high quality random numbers: arc4random()
or arc4random_uniform()
, just as in Objective-C.
They are in the Darwin
module, so if you haven't imported AppKit
, UIKit
, or Foundation
(which import it for you), you will need to import Darwin
.
Swift 4.2
Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You can call the random()
method on numeric types.
let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()