Error protocol

Swift includes the Error protocol, which forms the basis of the error-handling architecture. Any type that conforms to this protocol can be used to represent errors.

The Error protocol can be implemented by any type you define, but it’s especially well-suited to enumerations. As you learned in Chapter 16, enumerations are types with a fixed set of instances. This is ideal for representing specific error types.

Create a new playground. You are going to start your own bakery and use it to learn how to throw and handle errors using the Error protocol.

Add this code to your playground:

class Pastry {

let flavor: String var numberOnHand: Int

init(flavor: String, numberOnHand: Int) { self.flavor = flavor

self.numberOnHand = numberOnHand

}

}

enum BakeryError: Error {

case tooFew(numberOnHand: Int) case doNotSell

case wrongFlavor

}

The Error protocol tells the compiler that this enumeration can be used to represent errors that can be thrown. At a bakery you might not have enough of each item the customer wants, or it could be the wrong flavor, or you may not sell it altogether.

results matching ""

    No results matching ""