[swift-evolution] [Discussion]: Deprecate !-Unwrapping of Optionals

Pyry Jahkola pyry.jahkola at iki.fi
Mon Feb 29 03:26:32 CST 2016


> On 29 Feb 2016, at 10:40, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> 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 could not disagree more strongly.
> 
> Swift takes the position that assertions are good and that it's better to crash in an unexpected state than to limp on. Force unwrapping is an example of that philosophy. A force unwrap is a "this is not nil" assertion.


+(0.5 + 0.5). I think both of you have a point.

To me, even after soon two years of Swift, it's still extremely hard to visually see where forced unwrapping happens. I do not think we should recommend unsafeUnwrap though because we'd then trade a guaranteed crash for undefined behaviour on nil, which is definitely the wrong choice at least 95% of time.

Unless we're getting an option in Xcode to make the exclamation point U+0021 render as something like ❗️ (U+2757 U+FE0F), I think it would be more sensible to rather have a standard member function on Optional that does the same but more explicitly:

extension Optional {
  func unwrap() -> Wrapped {
    guard let value = self else {
      fatalError("unexpectedly found nil where unwrapping an \(Optional.self) value")
    }
    return value
  }
}

var x: String?
if x != nil { print(x.unwrap()) }

Indeed, with Optional.unwrap as a member function, we could even report where the assertion failed, which could be a big help when debugging errors that slipped into production:

extension Optional {
  func unwrap(file file: StaticString = #file, line: UInt = #line) -> Wrapped { ... }
}

print(x.unwrap())
fatal error: unexpectedly found nil where unwrapping an Optional<String> value: file /path/to/endless/swift-evolution/this-email-message.swift, line 36

There could be compiler magic to replace calls to Optional.unwrap with unsafeUnwrap in -Ounchecked builds.

Naming alternatives considered: forceUnwrap, forcedUnwrap, unwrapValue, assertUnwrap.

— Pyry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160229/42f4241e/attachment.html>


More information about the swift-evolution mailing list