2 Minute Tips: The Dark Secret of Optionals
<p>As fentanyl is to heroin; the <code>?</code> syntax gives a stronger kick at a much lower dose than <code>Optional<String></code>. The Swift Compiler metabolises it into the same end product: Getting high on type-safe nullability.</p>
<p>Let’s end with a use case for this forbidden knowledge.</p>
<p>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.</p>
<p>Your navigation logic might look like this:</p>
<pre>
if let hasSeenOnboarding = UserDefaults.standard.value(forKey: "hasSeenOnboarding") as? Bool,
!hasSeenOnboarding {
showOnboarding()
}
} else {
showOnboarding()
}</pre>
<p>With an explicitly typed optional, you can simply write:</p>
<p><a href="https://medium.com/@jacobmartinbartlett/2-minute-tips-the-dark-secret-of-optionals-d025a294ada0">Visit Now</a></p>