Swift – Random Number

To generate a random number in Swift, use Int.random() function.

Int.random() returns a number, that is randomly selected, in the given range. We can also specify the generator, using which the random value has to be generated.

Example

In this example, we will generate a random number in the range 1…99. Int.random() with the range 1…99, will return a number between 1 and 99, of course including 1 and 99.

main.swift

var n = Int.random(in: 1...99)
print("Random Number = \(n)")

Output

Random Number = 78

Generate N digit Random Number

To generate N digit random number, we may specify the range using smallest and largest of the N digit number. For example, to generate a random number of length 5, we can specify the range 10000…99999 to random() function.

main.swift

var n = Int.random(in: 10000...99999)
print("Random Number = \(n)")

Output

Random Number = 63859

Conclusion

In this Swift Tutorial, we learned how to generate a random number in Swift, using Int.random() function.