Codable

Most iOS applications are, at base, doing the same thing: providing an interface for the user to manipulate data. Every object in an application has a role in this process: Model objects are responsible for holding on to the data that the user manipulates. View objects reflect that data, and controllers are responsible for keeping the views and the model objects in sync.

So saving and loading data almost always means saving and loading model objects.

In LootLogger, the model objects that a user manipulates are instances of Item. For LootLogger to be a useful application, instances of Item must persist between runs of the application. In this chapter, you will make the Item type codable so that instances can be saved to and loaded from disk.

Codable types conform to the Encodable and Decodable protocols and implement their required methods, which are encode(to:) and init(from:), respectively.

    protocol Encodable {
        func encode(to encoder: Encoder) throws
    }

    protocol Decodable {
        init(from decoder: Decoder) throws
    }

(Do not worry about the new throws syntax; we will discuss it later in this chapter.)

Although your types can conform to either one of these protocols, it is common for types to conform to both. Apple has a protocol composition type for types that conform to both protocols called Codable.

    typealias Codable = Decodable & Encodable

Your Item class does not currently conform to Codable. Open LootLogger and add this conformance in Item.swift.

Listing 13.1  Declaring conformance to Codable (Item.swift)

class Item: Equatable, Codable {

The Codable protocol requires the two methods required by Encodable and Decodable. You have not implemented either of these methods in Item. However, build the project and you will notice there are no errors. What is going on here?

Any codable type whose properties are all Codable automatically conforms to the protocol itself. Item satisfies this requirement, as the types of its properties (String, Int, String?, and Date) all conform to Codable. (You will see how to conform to Codable manually in the section called For the More Curious: Manually Conforming to Codable near the end of this chapter.)

Now that Item can be encoded and decoded, you will need a coder. A coder is responsible for encoding a type into some external representation. There are two built-in coders: PropertyListEncoder, which saves data out in a property list format, and JSONEncoder, which saves data out in a JSON format. You are going to serialize the Item data using a property list. (You will see JSONEncoder in action in Chapter 20.)

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

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