Home
Swift
Random Numbers: arc4random
This page was last reviewed on Aug 23, 2023.
Dot Net Perls
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.
Some notes. 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.
A first example. This example uses the arc4random function. In Xcode you can scroll through a list of functions by typing a few characters like "ar."
Info Arc4random returns a random number. As we see in the output this number has a large range but is positive.
Here We use some logic in a repeat-while loop to test our random numbers. We use modulo division to terminate the loop.
repeat while
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 true
The 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.
Arc4random, seed. With arc4random, a different sequence is generated each time a program is run. No special seed value must be specified.
Important With arc4random, programs will not have the same results each time they are run.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.