Written by Alex Gibson, on June 6, 2017


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.


func save(){
        //save it
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(journalEntries){
            UserDefaults.standard.set(encoded, forKey: "JournalEntries")
        }
    }

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.


func startCodableTest(){
        if let jE = UserDefaults.standard.value(forKey: "JournalEntries") as? Data{
            let decoder = JSONDecoder()
            if let journalEntrs = try? decoder.decode(Array.self, from: jE) as [JournalEntry]{
                journalEntries = journalEntrs
            }
        }
    }

Obviously the name of this function is bad and I will leave that for you to change.  So there is only one thing left to do.  Go to our JournalEntry file and make JournalEntry conform to Codable


struct JournalEntry:Codable

That one addition to the struct makes all the magic happen.  Wow things do get better.  Hope you enjoyed and good luck persisting your data.