|
|
|
|
|
by jchb
2821 days ago
|
|
The idea of an option type (Optional in Swift) is to use it only for a variables truly assume a "none" value at some point.
With the guarantees of such a type it is easier to reason about the correctness of a program - compared to Objective-C where a pointer anywhere may be null at any time.
Optional shouldn't be used for most variables and parameters. `guard let param = param else { return }` should be something pretty rare. I would mostly expect to see that for weak self variables in completion blocks. Also, take into account that in Objective-C you can send any message to a nil pointer, and the result will be nil or 0 (for scalar types), as defined by the language standard. |
|
I'd agree if Swift was a general-purpose C++ replacement, but most developers use Swift to write Cocoa apps. viewController.navigationController is optional, view.superview is optional, label.text is optional; all of Apple's frameworks are built on mutable state where almost everything can be or become nil.
(We can make sure that most variables and parameters aren't optional, but that only pushes the problem to other lines of code.)
If we know that we've loaded a view controller from a storyboard, is `self.storyboard!.foo` really a code smell? What else should we do? The type system doesn't let us express what we know/assume about the situation, unless we completely sidestep Apple's controller infrastructure and write our own thing.
> Also, take into account that in Objective-C you can send any message to a nil pointer, and the result will be nil or 0 (for scalar types), as defined by the language standard.
Right, I am not saying that Objective-C handled this any better. But it boggles my mind that we have Swift's complicated type system now, and use it to rebuild an implicit source of errors from Objective-C.