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)

“Only documents and other data that is user-generated, or that cannot otherwise be recreated by your application, should be stored in the <Application_Home>/Documents directory and will be automatically backed up by iCloud.”

Caches Directory (.caches)

“Data that can be downloaded again or regenerated should be stored in the <Application_Home>/Library/Caches directory. Examples of files you should put in the Caches directory include database cache files and downloadable content, such as that used by magazine, newspaper, and map applications.
Use this directory to write any application-specific support files that you want to persist between launches of the application or during application updates. Your application is generally responsible for adding and removing these files. It should also be able to re-create these files as needed because iTunes removes them during a full restoration of the device. In iOS 2.2 and later, the contents of this directory are not backed up by iTunes.
Note that the system may delete the Caches/ directory to free up disk space, so your app must be able to re-create or download these files as needed.”

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 :^)