Let’s Simplify the Work with UserDefaults

Everyone has worked with UserDefaults in order to store some simple data and knows that working with that storage is easy as it can be. But today I’m going to improve the interaction with it a bit though! Let’s start with the most obvious solution and implement something new and elegant. 😌

Imagine we have some service — SettingsService. This service knows about the app’s settings — which theme is used (dark, light), whether notifications are enabled and so on. To implement it the majority of developers will think about the UserDefaults at first. Of course, it depends on the case, but let’s simplify it.

  1. Our first simplest solution:

For simplifying, I explicitly use UserDefaults.standard but in a real project you’d better to store it on a property and use DI of course.

2. The next step what I want to take is to get rid of Keys enum — use the #function instead:

Looks better! Let’s go further :)

3. Subscript time! We’ve just wrapped the value(forKey:)function into a subscript with a generic:

It already looks pretty neat! But what about Enums? 🤔

There’s a place for refactoring!

4. Let’s write a similar subscript only for RawRepresentable values:

Ready for production! Please, be aware that this extension is only applied for enums with RawRepresentable presentation.

Don’t miss a chance to subscribe to my telegram channel! Be the first to know interesting news, articles from the iOS World!

I hope you enjoyed my extensions! If you know any ways of improving it — let me know! There’s a final extension on UserDefaults. Feel free to test it out! :)

That’s me during ITC build processing.

Shaggy iOS Engineer. Reactive, Open-Source lover and Retain-cycle detector :)