Error handling

Now let's explore how we can do error handling in Swift. We will begin by looking at some of the patterns we used prior to Swift 2.0. These patterns are still valid, and sometimes preferred, even with the do-catch blocks that were introduced in Swift 2.0 because there are times we want something simpler and we also do not want to have do-catch blocks everywhere in our code.

We will use a Drink structure that is similar to the code we created in Chapter 1, Object-Oriented and Protocol-Oriented Programming, to demonstrate the various error handling methods. Here is the code for the Drink structure:

struct Drink {
    var volume: Double
    var caffeine: Double
    var temperature: Double
    var drinkSize: DrinkSize
    var description: String
    
    mutating func drinking(amount: Double) {
        volume -= amount
    }
    mutating func temperatureChange(change: Double) {
        temperature += change
    }
}

For each error handling pattern, we will add a single error condition for the drinking() method that is returned or thrown if the amount parameter (which specifies how much we are drinking) is greater than the volume property (which defines the amount remaining in the drink). We will also define two error conditions for the temperatureChange() method that will be returned or thrown if the drink gets too hot or too cold.

Now let's begin with our error handling patterns. The first pattern that we will show is how to use return values to indicate success or failure.