Swift UserDefaults




What is UserDefaults?


UserDefaults is an interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app. It's suitable for storing simple data types such as integers, floats, strings, booleans, and URL objects. For more complex data, you can use UserDefaults to store Data objects, which can be created from encoded instances of classes or structs.


How to Use UserDefaults



Saving Data


To save data to UserDefaults, you use the standard singleton instance of UserDefaults and call methods on it to set values for specific keys. Here's an example of how to save a string:


UserDefaults.standard.set("John Doe", forKey: "userName")


Retrieving Data


To retrieve data, you use a method corresponding to the type of data you expect. If the key doesn't exist, these methods return a default value (like 0 for integers, false for booleans, or nil for objects). Here's how you might retrieve the string saved earlier:


let userName = UserDefaults.standard.string(forKey: "userName") ?? "Default Name"


Removing Data


To remove a key-value pair from UserDefaults, you can use the removeObject(forKey:) method:


UserDefaults.standard.removeObject(forKey: "userName")