Try, throw, do and, catch - Swift error handling
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; indeed, good error handling can separate a good app from a great app.
Swift provides a deliberate and flexible pattern for handling errors, helpfully allowing specific errors to be cascaded through a complex system.
How to do it...
To examine error handling, we will model a process that can go wrong, and that, for me, 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 }
- Next, we will create an object to represent the meal we will be cooking, which will hold the state of the meal as it moves through...