Optionals in Swift: We love them and so will you! - Clearly Innovative | Web and Mobile DevelopmentClearly Innovative | Web and Mobile Development

What are Swift Optionals and why do we think they’re so great?


Optionals bring that extra level of error checking to Swift. Optionals allow for nil data to be passed to or returned from functions.

The idea behind Optionals is that you have written a program that expects to return a certain type of data to its user. If that data does not exist upon execution of the function, your program would inevitably crash!! And we all know nobody likes a broken program.

Developer Struggles


Optionals To the Rescue!

The function above takes a parameter and searches the employees array, if the name passed in matches an employee in the array, it would return the employee’s name. if not nothing happens and then the compiler would complain that you’re missing a return statement.

The function would complain that it’s missing a return statement, even though we did provide one.

The reason for this is that the return statement that’s placed inside the if clause is a conditional return statement and will only get executed if the name variable passed into the function matches an employee in our employees array.

A common solution to this problem is to have have a return statement at the end of our function block that returns an empty string and then plug that function into an if statement and check for nil or and empty string, that’s far too much work.

In comes Optionals to our defense. By suffixing the return type of our function with a ‘?’ we can then indicate to the compiler that our function will be returning an Optional. See the function block below.

Now our function can safely return nil, if our name parameter does not exist inside the employees array.


Optionals Unwrapping

But WAIT!!!

Unfortunately we are not done yet. When a function returns an Optional, the data structure that’s returned is a Struct and thus to access our returned property we first have to unwrap the Optional.


Method 1

Direct unwrapping.

As mentioned earlier, when a function returns an Optional, the data type that is returned is a struct so in our case to access the string component returned from our function, we can directly unwrap it by suffixing the our container variable with a ‘!’



would return to us the string value of the employee’s name that was passed into the function.


Method 2

Our previous method was a tad bit inefficient, because when our function returned nil when we try to unwrap it using the ‘!’ character, our program would crash.

The more appropriate method to unwrap an Optional when we are not sure if a value is returned or not, would be to use the ‘if let syntax.’

for example:


Ranjay Salmon | ranjay@clearlyinnovative.com


Have further questions or want to work with us to build a Swift app? Talk to us!