Optionals in Swift

Easily detect the absence of value in variable or constant using Optionals

Optional is an enum that has 2 states, the first state is where there is a value and that value is of some type for example Int, and the other state is nil where there is no value at all.

Optionals help you detect the absence of value for any type not just classes, so an Int or Bool might be Optional.

For Example Int? is an Optional Int, it means that it might contain an Int or nothing at all.

To create an optional add question mark(?) to the type

let totalCount : Int?
var firstName : String?

Optionals default value

If you didn’t provide a default value to an optional variable it will be set to nil by default

//set default value to 8
var totalCount : Int? = 8
//set to nil because you didn't provide a default value
var firstName : String?

Forced unwrapping using If Statement

To read the value inside optional variable you have to unwrap it but first you must ensure that it is not nil.

We can use the If Statement to compare the variable against nil using (==) or (!=)

if totalCount != nil {
      print("there is a value in totalCount")

Once you are sure that there is value in the variable you can unwrap the variable to access the underlying data.

You access the underlying value by adding exclamation mark (!)

if totalCount != nil {
      print("there is a value in totalCount \(totalCount!)")

Optional Binding

Using (if let) or (if var) you can check if the optional variable has a value and then you assign that value to a temporary constant that is available only in the first branch of the if statement, you can also use guard or while statements

if let tempTotal = totalCount {
     //no need to use ! here
     print("use tempTotal here \(tempTotal)")

Implicitly Unwrapped Optionals

If you are sure that an Optional will always have a value after it is defined (like IBOutlet) then you can define it as Implicitly Unwrapped Optional.

To define Implicitly Unwrapped Optional you just use ( ! ) instead of ( ? ) in optional definition.

To unwrap it just don’t use ( ! ) mark.

let domainName : String! = "ios-Tutorial"
let tempName = domainName

Leave a Reply

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