Psst! Come here, I’ll let you in on a secret.
Question marks, exclamation marks, chaining, coalescing? Optionals must be some Swift language magic, right?
You couldn’t be further from the truth. Open Xcode and type this in:
Optional<String>.none()
Now, quick, before anyone sees you!
CMD+Click
on the word Optional
. Press enter.
Like breaking out of the Matrix, we finally see the code that makes up our world — the world of the the Swift Standard Library. The source code for Optional.
@frozen
public enum Optional<Wrapped>: ExpressibleByNilLiteral {
case none
case some(Wrapped)
}
Your whole life was a lie.
Optionals were a 2-case enum the entire time.
It’s true.
Optionals are just part of the Swift Standard Library.
The ?
, !
, and ??
you know and love?
Syntax sugar, my friend.
As fentanyl is to heroin; the ?
syntax gives a stronger kick at a much lower dose than Optional<String>
. The Swift Compiler metabolises it into the same end product: Getting high on type-safe nullability.
Let’s end with a use case for this forbidden knowledge.
Imagine you need to store a flag in User Defaults, or, heaven forbid, the Keychain, to signify whether the user has been through your app onboarding.
Your navigation logic might look like this:
if let hasSeenOnboarding = UserDefaults.standard.value(
forKey: "hasSeenOnboarding"
) as? Bool,
!hasSeenOnboarding {
showOnboarding()
}
} else {
showOnboarding()
}
With an explicitly typed optionals, you can simply write:
if UserDefaults.standard.value(
forKey: "hasSeenOnboarding"
) != Optional<Bool>.some(true) {
skipOnboarding()
}
p.s. yes, I know that
bool(forKey:)
exists on UserDefaults already.