C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Arc4random: This 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.
RepeatSwift program that uses arc4random
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
Output
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.
Important: With arc4random, programs will not have the same results each time they are run.
Swift program that shows random numbers
import Foundation
// With arc4random we do not need to seed the random number generator.
// ... A difference sequence is generated each time.
print("Test")
for i in 0...3 {
print(arc4random())
}
Output
Test
2350561563
3189423288
1041162380
2422311100
(Second run)
Test
1179004133
1484905321
2378084349
2120303966