Swift 4 - Saving Codable structs? Let’s make things even easier!

Update: I recently released Disk, a sweet little framework that makes persistence on iOS super easy. I’d love for you to check it out!

Working with Codable structs is an absolute delight, but it can get kind of tiresome having to instantiate JSONEncoder and JSONDecoder whenever we want to retrieve or store model data. I threw together a little helper class called Storage this weekend that helps with this process tremendously.

Let’s say we have a model called Message

… and we want to store an array of Messages to disk…

… and later we might even want to retrieve it:

(If you option + click messagesFromDisk, it’ll show its type as [Message], pretty neat, huh?)

If you’ll notice, I’m storing messages.json to .documents. There’s a few places on the user’s iOS device you can store data to, but Apple’s guidelines dictate that you store data primarily in two places:

Documents Directory (.documents)

Caches Directory (.caches)

Here’s a few other helper methods included in Storage:

And finally here’s the Storage class used in the examples above:

Let me know what you think :^)

iOS Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store