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 optional, you can simply write: