Manage UserDefaults Keys with Enum
Clean and easy to implement
UserDefaults is commonly used to store simple persistence data or state. But, improper key management would lead to future major problem and code messiness. Moreover, sometimes the typo of key name might result to untraced bugs.
Therefore, let’s try to manage the UserDefaults keys in a cleaner way using Enum (Enumeration). Enum is a very powerful data type to group related values in a type-safe way.
So, we are going to use the Enum with String and CaseIterable. The good thing is programmer will always use the pre-defined keys in the Enum and we don’t have to worry about using incorrect key names. That’s is truly awesome!
Create Helper Class
Let start writing our custom helper class, called
CustomUserDefaults. (You may try this in Playground first to be quick)
This class can simply be used with below syntax. It is almost similar to common one, but this time we got the key as Enum items. Hoorayyy!
Take note that from the
CustomUserDefaults class, the get function will return result in `Any?` type. In order to make it unwrapped value, use common
if let or
guard syntax with casting of preferred type. See example below, the
savedName is cast to String type and checked if nil or not.
Yeah, basically the helper class is ready to role! 🚀
Let’s add two more functions to give it more flexibility.
- A function to check if value is exist namely
hasValue(key:)to check the existence of value or nil
- A useful function called
removeAll()to clear all the stored values in UserDefaults. We usually need this when signing out user from the apps. No worries, the
CaseIterablewill do it for you in iteration part.
Great, now our helper class is much more complete and it should look like below.
What’s Next? Try it and extend more functionalities as you need. Thanks for reading. I hope you enjoy and try to implement into your project, so it will be much cleaner and readable.
“Learn. That’s how we grow our coding skills” ❤️