Bailing out with fatalError and precondition
It's comforting to think that, in the code you write, everything will always happen as expected, and your program can handle any eventuality. However, sometimes things can go wrong, really wrong; a situation can arise that you know is possible, but don't expect to ever happen, and the programs should terminate if it does. Swift has a way to define these situations, and in this recipe, we will look at two of them: fatalError
and precondition
.
Getting ready
Let's reuse our example from the previous recipe; we have an object that can be used to classify movie reviews based on how many stars out of ten the review gave the movie. However, let's simplify its use, and say that we only intend for a classifier object to classify one, and only one, movie review.
How to do it...
Let's look at some code that uses fatalError
and precondition
, and then we will look at how it works:
- First, we'll define the classification state and the movie review class:
enum ClassificationState...