Errors happen during programming. These errors may be due to your own code behaving in unexpected ways, or due to unexpected information or behavior from external systems. When these errors happen, it's important to handle them appropriately. Good error handling can separate a good app from a great app.
Swift provides a deliberate and flexible pattern for handling errors, allowing specific errors to be cascaded through a complex system.
In this recipe, we will discover how to define errors, and throw them when necessary.
How to do it...
To examine error handling, we will model a process that can go wrong, and for me, that is cooking a meal:
- First, let's define the steps involved in cooking a meal as states that the meal will transition through:
enum MealState {
case initial
case buyIngredients
case prepareIngredients
case cook
case plateUp
case serve
}
- Create an object to represent the meal we will be...