Handling persistent state with UserDefaults
UserDefaults
is a fundamental yet simple solution for iOS developers to store persistent information in a key-value format. We can easily store and fetch Boolean, int, string, arrays, and dictionary values with UserDefaults.
For example, this is how we store a Boolean in UserDefaults:
let defaults = UserDefaults.standarddefaults.set(true, forKey: "isUserLoggedIn")
And this is how we read it:
let defaults = UserDefaults.standardlet isUserLoggedIn = defaults.bool(forKey: "isUserLoggedIn")
The UserDefaults goal is not to store and retrieve large datasets – UserDefaults is a slow and unsecured solution for that use case. If we want to manage a local data store, we should use Core Data or SQLite for this purpose.
As mentioned earlier, UserDefaults is a very simple and straightforward tool. However, it still has some advanced capabilities we may need to know when preparing for our interview. Let’...