[swift-evolution] [Discussion]: Deprecate !-Unwrapping of Optionals
devteam.codafi at gmail.com
Mon Feb 29 08:54:38 CST 2016
I have to clarify here: I am not taking about .!, as!, as?, ?, etc. I am taking about making naked bang-unwrapping more difficult. That is, those cases when you write
let thing = optVal!
These are equivalent to naked unguarded dereferences in C-like languages and are, we can all agree, a code smell, not a feature. One would not ever recommend to a user of such languages that * or -> be used before checking that an object or region of memory was non-NULL. So, too, should we discourage this case by removing postfix-! from the language itself (notice it isn't even an operator, it is actually a part of the language).
2016/02/28 14:53、Developer <devteam.codafi at gmail.com> のメッセージ:
> 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). In addition, bang is incredibly hard to spot in code bases that use it because it blends in with Boolean negation (which, in itself, is notoriously hard to spot in other C-like-languages), harming readability and making code review more difficult. Finally, if the authors of a piece of code have such confidence in the existence of a value that they feel it safe to use force unwrapping, they should simply use a non-optional value and cut out a level of indirection and avoid the dangers of bang in the first place.
> Because of the above, I'd like to start a discussion about its deprecation and eventual removal in favor of either an unsafeUnwrap function or other extra-syntactic constructs. I don't intend for force-unwrapping as a concept to go away, as there will always be corner cases where it is necessary, but I don't believe it deserves to be so easy to do in a language that holds safety as a core tenant.
> Thanks all,
> ~Robert Widmann
More information about the swift-evolution