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

How to generate random numbers in iOS 8 and below

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.

Test your Swift today

Think you know Swift? My book Swift Coding Challenges will put your Swift skills to the test – it's perfect for job interviews and more!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>