Updated for Xcode 15
In these chapters we’ve covered one of Swift’s most important features, and although most people find optionals hard to understand at first almost everyone agrees they are useful in practice.
Let’s recap what we learned:
nil
inside.if let
to run some code if the optional has a value, or guard let
to run some code if the optional doesn’t have a value – but with guard
we must always exit the function afterwards.??
, unwraps and returns an optional’s value, or uses a default value instead.try?
– you’ll either get back the function’s return value, or nil
if an error is thrown.Optionals are second only to closures when it comes to language features folks struggle to learn, but I promise after a few months you’ll wonder how you could live without them!
TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.