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:
We can use
forced unwrap to get the value, but we must be sure that it has a value
NOTE: Optionals cannot be constants. You need to use
varto define them.
myBankAccountBalance as an optional variable, to use it it must be
But what happens if we are not sure if we have a value in the variable?
In this case we have to use
unwrappedBalancewill only exists inside of that code block.
We can also do an
Implicitly unwrapped options by using the
! on creation. This way: