Basic Swift, part 3 - Optionals

Swift Optionals

Optional is an instance variable that may or may not have a value.

In Swift is not possible to use a variable that is empty. Variables cannot be nil (will crash program if it happens). So by setting a variable to be optional, Swift is creating a bubble around that variable to protect it from ever being nil.

So if there is a variable that is possible that in some point in time will be nil, we have to declare it has optional, like this:

var myBankAccountBalance?    // (?) question mark defines optional variable

Forced Unwrap

We can use forced unwrap to get the value, but we must be sure that it has a value

myBankAccountBalance = 1.11
let myCurrentBalance = myBankAccountBalance!   // FORCED, since now we now that has a value

NOTE: Optionals cannot be constants. You need to use var to define them.

By declaring myBankAccountBalance as an optional variable, to use it it must be unwrapped.

Optional binding

But what happens if we are not sure if we have a value in the variable? In this case we have to use Optional binding:

if let unwrappedBalance = myBankAccountBalance {
  print("I have money: \(unwrappedBalance). WEEEE")
} else {
  print("Ups, no money again.")

unwrappedBalance will only exists inside of that code block.

Implicitly unwrapped

We can also do an Implicitly unwrapped options by using the ! on creation. This way:

var myCurrentBalance: Double! // we are sure this variable will have a value in some point in time
Share Comments
comments powered by Disqus