Random
In Swift 5.8, we compute random Ints with a Foundation function. With arc4random, we can begin a random sequence of numbers. Our program will begin a different sequence each time.
Arc4random is a good choice for random numbers in many Swift programs. But it is not sufficient for some—it is a pseudo-random number generator.
This example uses the arc4random function. In Xcode you can scroll through a list of functions by typing a few characters like "ar."
import Foundation // Use infinite "repeat while true" loop. repeat { // Get random number with arc4random. let number = arc4random() print("The computer selected: \(number)") // Check for multiple of 10. if number % 10 == 0 { print("Divisible by 10, stopping loop.") break } if number % 5 == 0 { print("Divisible by 5, you are a winner.") } } while trueThe computer selected: 1580707251 The computer selected: 2169372518 The computer selected: 2188614733 The computer selected: 2102187726 The computer selected: 1259434845 Divisible by 5, you are a winner. The computer selected: 4203979483 The computer selected: 3751678511 The computer selected: 1143995553 The computer selected: 1399438296 The computer selected: 4189143210 Divisible by 10, stopping loop.
With arc4random, a different sequence is generated each time a program is run. No special seed value must be specified.
import Foundation // With arc4random we do not need to seed the random number generator. // ... A difference sequence is generated each time. print("Test") for _ in 0...3 { print(arc4random()) }Test 2350561563 3189423288 1041162380 2422311100 (Second run) Test 1179004133 1484905321 2378084349 2120303966
With helpful Foundation methods, we generate random numbers in Swift. Arc4random is used for best pseudo-random results. It does not need a special seed.