NEW: Master Swift design patterns with my latest book! >>

How to generate random numbers in iOS 8 and below

Written by Paul Hudson    @twostraws

iOS 9.0 introduces Gameplay and its great new random tools, but if you have to support iOS 8.0 and earlier here's the code you're looking for:

let randNum = arc4random_uniform(6)

That will generate a number between 0 and 5. If you're looking for a random number between any two numbers, try this helper function:

func RandomInt(min: Int, max: Int) -> Int {
    if max < min { return min }
    return Int(arc4random_uniform(UInt32((max - min) + 1))) + min

That generates numbers inclusive, meaning that RandomInt(0, 6) can return 0, 6, or any value in between.

Available from iOS 2.0 – see Hacking with Swift tutorial 35

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Love Hacking with Swift?

Get all 40 projects in PDF and HTML: buy the Hacking with Swift book! It contains over 1300 pages of hands-on Swift coding, and will really help boost your iOS career

Click here to visit the Hacking with Swift store >>