You can't chain the optional binding like this:
if let constantName = someOptional && constantName = someOptional2 {}
but in Swift 1.2 you can write this:
if let constantName = someOptional, constantName = someOptional2 {}
What's going on here?
Optionals are their own type and are Swift's way of providing compile time checking for nil
. When you type var potentialValue : Int?
you are not using some special Int, you are using the Optional type, which is essentially an empty enum. This is why you often have to unwrap the optional with the !
as this allows you to access what's inside (if there is anything inside). If the optional contains no value (i.e. the enum is empty) then it has a value of None
. If the optional is not empty then it has a value of Some
and an associated value of whatever type you are using - so in this case an Int.
This:
if (someOptional != nil){
let constantName = someOptional!
}
is the same as using this:
if let constantName = someOptional {}
which is called optional binding. You'll notice that the second version here is a little more readable and you don't have to explicitly unwrap the optional using the !
.
It evaluates to true when the optional's value is Some
and not None
- in other words, when the optional is not nil. (Notice that you can still check for nil
if you like and you can also change an optional's value back to None
by writing someOptional = nil
.
Something else that hasn't been mentioned is that you can use ??
(called the nil coalescing operator) to give an optional a default value if it doesn't have one. For example:
let constantName = someOptional ?? 100
Here someOptional
will be unwrapped if it has a value but if it doesn't then the value 100
is used instead.
I find it useful to remember that optionals are their own type in Swift. They aren't a fancy version of the type that you are saying they contain.