Error Handling

It is often useful to have a way of representing the possibility of failure when creating methods. You have seen one way of representing failure throughout this book with the use of optionals. Optionals provide a simple way to represent failure when you do not care about the reason for failure. Consider the creation of an Int from a String.

    let theMeaningOfLife = "42"
    let numberFromString = Int(theMeaningOfLife)

This initializer on Int takes a String parameter and returns an optional Int (an Int?). This is because the string may not be able to be represented as an Int. The code above will successfully create an Int, but the following code will not:

    let pi = "Apple Pie"
    let numberFromString = Int(pi)

The string "Apple Pie" cannot be represented as an Int, so numberFromString will contain nil. An optional works well for representing failure here because you do not care why it failed. You just want to know whether it was successful.

When you need to know why something failed, an optional will not provide enough information.

Swift provides a rich error handling system with compiler support to ensure that you recognize when something bad could happen. You are seeing an example of that now: The Swift compiler is telling you that you are not handling a possible error when attempting to encode allItems.

If a method can generate an error, its method signature needs to indicate this using the throws keyword. Here is the method definition for encode(_:):

    func encode(_ value: Encodable) throws -> Data

The throws keyword indicates that this method could throw an error. (If you are familiar with throwing exceptions in other languages, Swift’s error handling is not the same as throwing exceptions.) By using this keyword, the compiler ensures that anyone who uses this method knows that it can throw an error – and, more importantly, that the caller handles any potential errors.

To call a method that can throw, you use a do-catch statement. Within the do block, you annotate any methods that might throw an error using the try keyword to reinforce the idea that the call might fail.

In ItemStore.swift, update saveChanges() to call encode(_:) using a do-catch statement.

Listing 13.3  Using a do-catch block to handle errors (ItemStore.swift)

func saveChanges() -> Bool {
    do {
        let encoder = PropertyListEncoder()
        let data = encoder.encode(allItems)
        let data = try encoder.encode(allItems)
    } catch {

    }

    return false
}

If a method does throw an error, then the program immediately exits the do block; no further code in the do block is executed. At that point, the error is passed to the catch block for it to be handled in some way.

Next, update saveChanges() to print out the error to the console.

Listing 13.4  Printing the error (ItemStore.swift)

func saveChanges() -> Bool {
    do {
        let encoder = PropertyListEncoder()
        let data = try encoder.encode(allItems)
    } catch {
        print("Error encoding allItems: (error)")
    }

    return false
}

Within the catch block, there is an implicit error constant that contains information describing the error. You can optionally give this constant an explicit name. Finally, update saveChanges() to use an explicit name for the error being caught.

Listing 13.5  Using an explicit error name (ItemStore.swift)

func saveChanges() -> Bool {

    do {
        let encoder = PropertyListEncoder()
        let data = try encoder.encode(allItems)
    } catch let encodingError {
        print("Error encoding allItems: (error encodingError)")
    }

    return false
}

There is a lot more that you can do with error handling, but this is the basic knowledge that you need for now. We will cover more details as you progress through this book.

You now have encoded the items array into Data using a property list format. Now you need to persist this data to disk. You can build the application now to make sure there are no syntax errors, but you do not yet have a way to kick off the saving and loading. You also need a place on the filesystem to store the saved items.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.111.9