Connect with us

Articles

Safer and cleaner UserDefaults and AppStorage

If you’ve ever written code for an iOS or macOS application you’d have, for sure, encountered User Defaults. Still, for the sake of the structure of the article, here’s a textbook definition of what UserDefaults is:

UserDefaults: An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.

The problem

UserDefaults is a key-value pair store where you can set and retrieve elements from persistent memory using a “key”. I detest using hard-coded strings for anything in my application. I try to avoid stringly typed values until it’s necessary. The UIKit framework and Swift language in general do a very good job of avoiding unnecessary string matching (Foundation still has it in a few places such as HTTP methods like “POST” or “GET”). According to me, there are a few issues with using string matching in our code- spelling mistakes, casing mismatch, and might I argue that it looks really out of place in our codebase.

Currently, to set a value to the UserDefaults store you’d have to write something like this:

UserDefaults.standard.set(true, forKey: "isLoggedIn")

This code sets true to a key isLoggedIn and stores it in the UserDefaults store. We’d usually use something like this when we have to check if the user has logged in to then show them a different set of views compared to if they haven’t logged in.

To access the value you’d have to do this:

UserDefaults.standard.bool(forKey: "isLoggedIn")

This works fine and is how UserDefaults is meant to be accessed. But, I’d like to argue that this method is highly unsafe. For starters, it is extremely easy to make a typo while typing out the key. Additionally, if another developer joins your team or contributes to your open source project and they’re used to using snake case they might mistakenly type “is_logged_in” out of habit. Finally, it’s hard to keep a track of what keys go where and ultimately you might end up with a mess of strings in your codebase.

Full ArticleSwapnanil Dhol @ Medium

Advertisement

Trending