Optionals in Swift

Agoi Abel
Agoi Abel
Jan 15, 2018 · 4 min read

Absent of Data

There are situations where we wish to accept data from users and also provide an opportunity for some of the data to be optionals, meaning they are not required but should be provided if available.

What is an Optional in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ?to any type:

var middlename: String?
var red: String = "Red"red = nil // error: nil cannot be assigned to type 'String'

How to create an Optional?

The simplest way to create an optional in swift is to add ? in front of the type like below

var middlename: String?
var middlename: Optional<String>

Using (unwraping) an optional

The simplest way to unwrap an optional is to add a !after the optional name.

Use If to Check for nil before force unwrapping:

Since it was nil that was passed to the variable when we initialized the Person struct, we can use an if statement to check for nil before unwrapping the Person struct like below

Using Optional binding:

With optional binding, though we are still using if, swift provide a way for us to use the if let statement then automatically unwrap it for us like below

Using Guard for early exit:

Guard provide a way to quickly exit when checking for the optional string and make our code much more cleaner hence there wont be need for if else statement.

I am happy to share this article with you. If you’ve enjoyed this article, do show support by giving a few claps 👏 . Thanks for your time and make sure to follow me or drop your comment below 👇

Agoi Abel

Written by

Agoi Abel