[swift-evolution] [Discussion]: Deprecate !-Unwrapping of Optionals
Dave Abrahams
dabrahams at apple.com
Mon Feb 29 16:35:17 CST 2016
on Sun Feb 28 2016, Developer <swift-evolution at swift.org> wrote:
> Optional values pervade Swift code and so there is a significant part
> of the language dedicated to manipulating them and using them safely.
> An optional value may be conditionally let-bound, guarded,
> pattern-matched on, given a default value with ??, or used with
> higher-order functions like map and flatMap without having to interact
> with partiality. A corner case, however, remains in the form of the
> postfix-! force-unwrap operator. At the term level, there is little
> reason to unwrap given the syntactic constructs above, and indeed code
> that does becomes brittle and, by its very nature, open to the dreaded
> "unexpectedly found nil while unwrapping an optional value" error (our
> very own NullPointerException).
Whether ! is a problem depends how you use it. IIUC it's very common
that you know an optional is non-nil unless there's a bug in your code.
In those cases, IMO, y! is far preferable in terms of maintainability to
if let x = y {
}
else fatalError("...")
and in terms of both maintainability *and* reliability, is much better
than:
if let x = y {
}
else {
// supposed "recovery" code that never actually gets executed
}
If people use y! to avoid dealing with cases that can actually arise in
correct code that's a problem, but I'm not sure taking away "y!" is the
cure.
--
-Dave
More information about the swift-evolution
mailing list