Introducing an “Unwrap or Throw” operator

This feels very similar to the guard statement.

guard URL(string: "https://google.com") != nil else {
    fatalError("WTF?")
}
guard URL(string: "https://google.com") != nil else {
    throw NSError(domain: "WTF", code: -2, userInfo: nil)
}
guard URL(string: "https://google.com") != nil else {
    throw UnwrapError.forceUnwrapFailed(text: "WTF?")
}
guard URL(string: "https://google.com") != nil else {
    showHelpfulErrorMessageAndQuit()
}

Also, force unwraps are not a “problem” — to quote @Ben_Cohen at the bottom of the second thread, they’re a legitimately useful part of the language. A force unwrap, when used properly, will not crash your program. If a force unwrap does crash your program, then you’re not using it properly.

3 Likes