Let’s talk about Optionals
There has been much complaining that Swift’s Optional type forces you to think about whether something may be nil
at every use, but aren’t we thinking about that already, just maybe implicitly?
Swift’s optionals simply formally enforce the thinking we already must consider when writing (or especially when reviewing!) Objective-C code. Perhaps we’ve internalized some rules for thinking about nil
when writing Objective-C, but with time we will for Swift as well. And if you have a momentary lapse of nil
-consideration, Swift reminds you instead of permitting that lapse.
Is that not a good thing?
Convenience with Optionals in Swift
You don’t have to write ridiculous nested if let
stataments in Swift when dealing with optionals. Optional chaining brings much of the convenience of messaging nil
in Objective-C, with added safety.
And the nil coalescing operator allows concisely falling back to a default value when you encounter a .None
optional.
What’s not to like?
And Objective-C isn’t nil-safe anyway
Yes, you can message nil
in Objective-C. This works most of the time, but some APIs will break if you pass them a nil
pointer, and with some limited exceptions the compiler can do nothing but stand by and watch.
(Which APIs can and can’t accept nil
? You’d better check the docs; there’s nothing in the method signature to help you.)
And what about the 1% of cases when messaging nil
and getting nil
back isn’t sane? Consider a hypothetical NSString
property, (BOOL) isEmpty
.
This method will work fine, until you have a nil
string, and you call nil.isEmpty
. This resolves to NO
, which will result in undesired program behavior. This is not nil
-safety.