Save Data in Your Swift App with PropertyListEncoder

Apple provides a PropertyListEncoder class to save data as a dictionary in a property list file. If your app’s data can be saved to a dictionary, using PropertyListEncoder provides a relatively easy way to save the data.

You must do the following to save app data with PropertyListEncoder:

  • Create a struct or class that conforms to the Codable protocol.
  • Create a CodingKeys enum for the properties in your struct or class.
  • Create a property list encoder and encode the data.

Creating the Struct or Class

For this article, I’m going to use a stripped down version of a struct I created in Phel to store an Apple help book’s Info.plist file. The following block shows the code for the struct:

Every property in the struct or class must also conform to Codable. If you can’t get the struct’s properties to conform to Codable, you must use the NSKeyedArchiver class to create the property list. The following article shows you how to use NSKeyedArchiver:

Saving with NSKeyedArchiver

Creating a CodingKeys Enum

It’s not mandatory to create a CodingKeys enum, but if you don’t create the enum, the property list encoder uses the name of the property as the key. In many cases the key must have a specific value. The CodingKeys enum lets you save the property list with the correct key names while letting you use clear property names in your code.

Add the CodingKeys enum inside your struct or class. Add a case for each property. The following code shows the enum for the HelpBookInfo struct.

When saving the property list, the file will use the key CFBundleName to store the name of the app, the key HPDBookTitle to store the name of the help book, and the key CFBundleIdentifier to store the help book’s bundle identifier.

Creating the Property List Encoder

Now you can create the property list encoder to save data. Start by creating an instance of PropertyListEncoder.

Property lists have two possible formats: XML and binary. Set the encoder’s outputFormat property to set the format.

Call the encode method to save the data. Supply the value that you want to encode. The encode method can throw errors so you must wrap the call in a do-try-catch block.

Adding the following method to the HelpBookInfo struct saves the help book information to an XML property list: