Crashes & exits are not acceptable in production code, and I’ve had to fix too many of them.
If a thing might be null/nothing but can't be used when it is, then you should write code that indicates your understanding of that case. Catching an error doesn't imply that your program should proceed, it communicates that you the programmer understood your system and anticipated its failure states. Proceeding or aborting is a secondary decision.
I don't disagree with this, but I can point out gobs of places in AppKit where Apple has arguably 'made an error' and I can't do anything about it. Or in third-party C libraries, which hold 99% of the functionality I ultimately need, and were not designed for having nice Swift programming interfaces.
I feel like everyone saying "never force unwrap!" must be writing pure-Swift standalone functions, with no dependencies, including the operating system. The API for writing items to the Mac clipboard still documents that it can throw exceptions, which are impossible to catch in Swift!
Obviously in F# or Haskell or C#8 or Rust this isn't a problem. But what we are talking about is: how do you handle, at runtime, in a language such as C#7 or Java, an null parameter being passed to a method that must return a value based on its parameter, but was passed null? It's a choice between very bad options where the least bad is usually to throw an ArgumentNullException or similar. Because there is nothing better to do.
There are cases where the programmer cannot express this to the compiler without a bottom type.
Right, hence why I'm suggesting that they can be useful if you don't put them everywhere and aren't using them as a band-aid to make your code compile :)
Is it a hard coded string that will never change? Force unwrapping is probably appropriate.
Is it based on user input? Then you should probably tell the user the string they entered isn't a URL.
- abort and unwind the current action
- retry something
- log something
- abort the app explicitly
- fallback to a different value
- comment why this is a known-possible failure state
- present a message to the user
...
But if you're creating it dynamically you should be guarding and throwing an error.
guard let data = notification.userInfo?["updatedItem"] as? Data else {
assertionFailure("Could not retrieve updated item")
return false
}
I am really being helpful here? If I see a crash on this line: let data = notification.userInfo?["updatedItem"] as! Data
I get essentially the same information, except it's done in a less verbose and easier-to-discover way. Whereas the first one is like adding this kind of useless comment: let x = 5 // Assign 5 to x1. ! used here is hard to spot, it's just few pixels of difference from ?.
2. assertionFailure is not the same as force unwrap, because it crashes only in debug mode. Ideally you would log it with some analytics so developers know if problem occured, but doing nothing is usually better than crashing the app.