How the VIP cycle fully encapsulate the UserDefaults details from the rest of your app

One of my students asked in my mentorship Slack group (a monthly subscription program that you can subscribe and unsubscribe on a monthly basis) about how to use UserDefaults properly in a Clean Swift architecture. I’ve seen multiple takes on this question in other blogs. Here’s my take:

Question: I’m a beginner programmer and the CleanStore sample app is still a little complicated for me. Do you have a basic example that takes a number input and saves it to UserDefaults so I can follow the logic of the VIP architecture? I.E One scene sets a few properties of an object in the UserDefaults and another view gets the properties from the UserDefaults store.


Answer: It’s important to understand there is a difference between high-level use case and low-level implementation detail. For example, ‘saving the user ID’ is a high-level use case, whereas ‘saving a number to UserDefaults’ is a low-level implementation detail. You can save the user ID to a file, plist, UserDefaults, or Core Data, …etc. That’s an implementation detail, and it should be able to change without affecting the rest of your app. So we don’t create and name a use case as SaveNumberToNSUserDefaults. Instead, we simply call it Login. When you trigger the use case, you know the user ID is saved for later use. But you don’t care the mechanism by which it is saved. If the mechanism changes to save to a plist, you still trigger the same Login use case. The invocation shouldn’t need to change.

Let’s create a hypothetical scenario. In the Welcome scene, the user is prompted to enter the userID and password. After the user is authenticated, he’ll be shown the Home scene which displays a greeting containing his userID. In this example, we can save the userID to UserDefaults in the Login use case of the Welcome scene. After login, we’ll then retrieve the userID in the ShowGreeting use case of the Home scene.

Here is a sample project to demonstrate a simple login system using the VIP cycle. It saves the userID in UserDefaults.

Raymond
I've been developing in iOS since the iPhone debuted, jumped on Swift when it was announced. Writing well-tested apps with a clean architecture has been my goal.

Leave a Comment

Your email address will not be published. Required fields are marked *