At this point, you should have a pretty strong grasp of what an optional is and how to use and debug it, but it will be valuable to look a little deeper at optionals to see how they actually work.
In reality, the question mark syntax for optionals is just special shorthand. Writing String?
is equivalent to writing Optional<String>
. Writing String!
is equivalent to writing ImplicitlyUnwrappedOptional<String>
. The Swift compiler has the shorthand versions because they are so commonly used. This allows the code to be more concise and readable.
If you declare an optional using the long form, you can see Swift's implementation by holding Command and clicking on the word Optional. Here, you can see that Optional
is implemented as an enumeration. Simplifying the code a little, we have:
enum Optional<T> { case None case Some(T) }
So we can see that an optional really has two cases: None
and Some
. None
stands for the nil case, while the Some
case...