Persisting Data with Swift 4 and Codable

Swift has changed a lot and if you are like me sometimes it is good and sometimes it seems like a lot of work. Well Swift 4 may bring some headaches but it also brings me great joy with the Codable Protocol. Now persisting data is so easy. If you ever made your classes conform to NSCoding there is quite a bit of boilerplate to get going. What about Structs? No problem with Codable. Let’s build a quick project to demonstrate how easy this is to use.

Download the starter project . Make sure you have Xcode 9 that can be downloaded from Apple Developer . Open the project with Xcode 9 and give it a run. If you tap the plus button you should see a new entry show in the table. If you swipe left you can delete the entry. Now rerun the application and you will see that the records are not persisting. That is what we are going to work on now.

First visit the save function that is already defined. Here we will save to user defaults but you could save it to the file system as well. We are also going to save the array journalEntries declared at the top of the file. Luckily Array conforms to Codable so our save function will look like this.

That’s it. Now to the startCodableTest function that basically loads our persisted data up from user defaults and is called in viewDidLoad. You can see the starter function already unpacks the data from UserDefaults so all we have to do is decode it to our array of JournalEntry structs. The function in it’s entirety is below.