Overview - Why Optionals
suggest changePrograms often need to distinguish a variable that has a value from one that does not. For reference types, such as C pointers, a special value such as null can mean “no value.” For value types, such as an integer, that is harder. A nominated value such as -1 can be used, but every reader has to agree on that convention, and the sentinel can no longer be a normal value.
Swift lets any variable be declared optional. A ? after the type means a normal optional. A ! means an implicitly unwrapped optional: it is still optional, and it unwraps when used. See Types of optionals.
For example,
var possiblyInt: Int?
declares a variable that may or may not contain an integer value.
The special value nil indicates that no value is currently assigned to this variable.
possiblyInt = 5 // possiblyInt is now 5
possiblyInt = nil // possiblyInt is now unassigned
nil can also be used to test for an assigned value:
if possiblyInt != nil {
print("possiblyInt has the value \(possiblyInt!)")
}
Note the ! in the print statement, which unwraps the optional value.
As an example of a common use of optionals, consider a function that returns an integer from a string containing digits; It is possible that the string may contain non-digit characters, or may even be empty.
How can a function that returns a simple Int indicate failure? It cannot do so by returning any specific value as this would preclude that value from being parsed from the string.
var someInt: Int
someInt = parseInt("not an integer") // How would this function indicate failure?
In Swift, that function can return an optional Int. Failure is a return value of nil. parseInt here is only a sketch of that idea.
var someInt: Int?
someInt = parseInt("not an integer") // nil if parsing fails
if someInt == nil {
print("That isn't a valid integer")
}