How to Create a Random Int Number in Swift 2 - Swift Tips 7

Good random numbers in iPhone apps are really important (the same is true for the lottery!). A good random number is from a range [start, end] that gives every value an equal probability of occurring.

An equal probability means that if you were to flip a coin—you should always get close to 50% heads and 50% tails over 100 coin tosses.

Download the sample Xcode project that shows how to create random Int numbers in Swift with a working iPhone app.

Swift Random Int Range

In Swift you should use the arc4random_uniform(N) function because it creates better random numbers (i.e.: equal probability).

arc4random_uniform(N) creates a number within from [0, N - 1], which means if you want numbers in the range [0, 100] you need to call arc4random_uniform(N + 1).

  1. Random Int [A, B] where A < B

    let A: UInt32 = 10 // UInt32 = 32-bit positive integers (unsigned)
     let B: UInt32 = 20
     let number = arc4random_uniform(B - A + 1) + A
  2. Random Int [0, 100]

    // Using the equation (100 - 0 + 1) + 0 becomes (101)
     let number = arc4random_uniform(101) // [0, 100]
  3. Random Int [1, 100]

    // Using the equation (100 - 1 + 1) + 1 becomes (100) + 1
     let number2 = arc4random_uniform(100) + 1 // [1, 100]
  4. Random Int [50, 100]

    // Using the equation (100 - 50 + 1) + 50 becomes (51) + 50
     let number3 = arc4random_uniform(51) + 50 // [50, 100]
  5. Unsafe: Swift method for a random Int within [A, B] where A < B

    Swift is strongly-typed which means that you need to explicitly change numbers that are Int into UInt32 and vice versa for the code to compile. Use the Int() and UInt32() initializers to convert between the types.

    func unsafeRandomIntFrom(start: Int, to end: Int) -> Int {
         return Int(arc4random_uniform(UInt32(end - start + 1))) + start
     unsafeRandomIntFrom(50, to: 100)  // positive ascending ranges work
     unsafeRandomIntFrom(-50, to: 100) // negative ranges work!
     //unsafeRandomIntFrom(500, to: 100) // Crash! EXC_BAD_INSTRUCTION

    Crash: Technically this will crash if A > B with a EXC_BAD_INSTRUCTION because the parameter of arc4random_uniform() is UInt32 and can only hold positive 32-bit integer values.

  6. Safe Swift method for a random Int within [A, B]

    func randomIntFrom(start: Int, to end: Int) -> Int {
         var a = start
         var b = end
         // swap to prevent negative integer crashes
         if a > b {
             swap(&a, &b)
         return Int(arc4random_uniform(UInt32(b - a + 1))) + a

Int Type Extension

You can make the randomIntFrom(_:end:) a static function on the type Int using a static function. This code block is then reusable in any of your projects to make random number generation simple.

extension Int {
    func randomIntFrom(start: Int, to end: Int) -> Int {
        var a = start
        var b = end
        // swap to prevent negative integer crashes
        if a > b {
            swap(&a, &b)
        return Int(arc4random_uniform(UInt32(b - a + 1))) + a

Where Does arc4random_uniform() Come From?

This random function is actually written in the C programming language (which you can use in Swift!). Read the arc4random man page (i.e.: manual page) for all the details.

Download the Code

Download the sample Xcode project that shows you how to create random Int numbers in Swift with a working iPhone app.

You can play change the range of numbers with the iPhone app to see how to use the arc4random_uniform() function correctly in your own apps.

How to Create Outlets and Actions in Xcode Using Swift - Swift Tips 6

Xcode with the Assistant Editor (Venn Diagram button) let's you connect code and UI (user interface) files together.

In order for you to make your UI interactive, you need to create connections from the UI to your related code files. These connections give Xcode names that you can use in your code file to modify how something looks programmatically or to respond to user input (button tabs, sliders, switches, etc). There are two primary connections you will create in Xcode: outlets and actions.


Outlets enable you to give a UI element a name that you can use in your code. You can create a connection from a label to your code file using an outlet.

Outlets will look like:

@IBOutlet weak var textLabel: UILabel!

You can modify properties associated with your UI element, like text and textColor for UILabel objects.


Actions let you trigger things that can happen in response to user input. When a user moves a slider, enters a date, or types their name you can run a chunk of code to respond to it.

Actions will look like:

@IBAction func buttonPressed(sender: AnyObject) {

    print("hi developer")

    textLabel.text = "you pressed me "

Creating Outlets and Actions

  1. Open the Assistant Editor
  2. Right-click and drag from your UI element (i.e. label) to the code file
  3. Xcode auto inserts code for you to create the name and connection

Variables and Properties

You can also create variables and properties in your Swift code files. For ViewController.swift files it is easier to initialize variables and properties when you declare them, or in your viewDidLoad() method.

Swift Tips Source Code

Grab the source code for this Swift Tip and many more at:

3 Common Crashes for Beginner iPhone Developers in Xcode using Swift

3 common crashes for beginner iphone developers in xcode using swift

As you work with your first iPhone app you will inevitably run into different crashes. The three most common crashes are what every beginner encounters. If you know what to look for, you can avoid these in the future.

Two of the crashes are real crashes and one is because you clicked and mistakenly added a breakpoint, which is used for finding bugs.

Here are the three crashes and how to fix them:

  1. Breakpoint Crash

    • Problem: Thread 1: breakpoint 1.1
    • Why: You clicked in the gutter left of your code and added a blue flag.
    • Solution: Delete or disable the breakpoint (blue flag) from the code gutter.
  2. Storyboard IBOutlet Crash

    • Problem: Thread 1: signal SIGABRT
    • Console:

      Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<ViewController 0x7fbd74a090d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key spellingMistakee.'

    • Why: You deleted an Outlet/Action connection in code or renamed it (i.e. spelling mistake).

    • Solution: Right-click on the UI element and remove the old Outlet/Action connection mentioned as the key in the top of the Console output.
  3. Nil Optional Crash

    • Problem: Thread 1: EXC_BAD_INSTRUCTION
    • Console:

      fatal error: unexpectedly found nil while unwrapping an Optional value

    • Why: You removed a UIView IBOutlet connection and then used the IBOutlet variable in code. The variable has no value until you reconnect it to the UI element.

    • Solution: Right-click and drag from the UI element to the IBOutlet property that Xcode stopped at with the EXC_BAD_INSTRUCTION.