Using Guard Statements to Make Optional Binding Variables more Accessible

The golden rule for dealing with optionals is to make sure they are safely unwrapped. Otherwise you are just begging for future unexpected behavior that causes a nil somewhere and crashes your beautiful app.

Quick refresher – an optional value may either have a value or nil. Before you can do anything with an optional value (ex. addding it to something else), you need to unwrap it. Otherwise you get an error.

//Declaring a variable named 'mightBeNil' of type Optional Int, with a value of 5
var mightBeNil: Int? = 5

print (mightBeNil)
//Optional(5)

print (4 + mightBeNil)
//Error

Safely unwrapping an optional with optional binding

The most common and safe way of unwrapping an optional is optional binding.

var mightBeNil: Int? = 5

if let mightBeNil = mightBeNil {
    print ("No longer optional: \(mightBeNil)")
    //No longer optional: 5
    print (4 + mightBeNil)
    //9
}

mightBeNil is unwrapped, removing the optional part and keeping the 5. Now it can be printed, or used in a calculation.

Simple, except you can only use that newly unwrapped optional from within the if let statement. What happens if you try using it outside of the statement?

var mightBeNil: Int? = 5

if let mightBeNil = mightBeNil {
    print ("No longer optional: \(mightBeNil)")
}

print (4 + mightBeNil)
//Error

Using Guard to keep accessibility

If you want to access that newly unwrapped optional outside of the if let, Guard comes in handy. However, for this to work, it needs to be used in a function or loop.

First, here is the above example, used in a function, resulting in the same error.

var mightBeNil: Int? = 5

func superUnwrap() {
    if let mightBeNil = mightBeNil {
        print ("No longer optional: \(mightBeNil)")
    }
    print (4 + mightBeNil)
}

superUnwrap()
//Error: the unwrapped mightBeNil is not accessible outside of if let

But now let’s change this to a guard statement.

var mightBeNil: Int? = 5

func superUnwrap() {
    //Try to unwrap the optional, else return (exit out of the function)
    guard let mightBeNil = mightBeNil else {return}
    print (4 + mightBeNil)
}

superUnwrap()
//9

This allows for outside access, and if the optional is actually nil, it won’t run the print line. It also makes coding more concise. Just remember: if you try this without a function, you’ll get error: return invalid outside of a func.

Guard can also be used with other control transfers statement like break, continue, or throw. Another example, this time in a for in loop.

var mightBeNil: Int? = 5

for i in 1...5 {
    guard let mightBeNil = mightBeNil else {break}
    print (i + mightBeNil)
}

//6
//7
//8
//9
//10

Leave a Comment

Your email address will not be published. Required fields are marked *