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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 23, 2023 (edit).