Q. What are User Defaults?
Ans. UserDefaults in Swift is a class that stores small amounts of data such as user preferences and application settings.
We can store preferences like the user’s favourite color or save state like “user has activated button”.
It allows us to save and retrieve data in key-value pairs, similar to a dictionary.
Data stored using UserDefaults
is typically stored in a property list, a type of file that can be used to store structured data.
Q. How to retrieve values from User defaults?
Ans. The object(forKey:) method in UserDefaults is a common way to retrieve values associated with a specific key. This method returns an optional value of type Any?, meaning it can either contain the value associated with the key (if it exists) or be nil if there’s no value for that key.
//Access Shared Defaults Object
let userDefaults = UserDefaults.standard
// Get Value
userDefaults.object(forKey: "someKey")
Additionally, the UserDefaults class offers several convenience methods for fetching values of specific types. For instance, if you want to obtain a boolean value associated with a particular key, you can use the bool(forKey:) method. In cases where no corresponding key–value pair exists, invoking bool(forKey:) will return a false value.
// Access Shared Defaults Object let userDefaults = UserDefaults.standard // Read Boolean let value = userDefaults.bool(forKey: "someKey")
Some convenience methods-
Note –
When retrieving values from UserDefaults, it’s important to be mindful of the return types to correctly interpret the results. Consider the following guidelines:
- If you use integer(forKey:), you will receive an integer if the key exists; otherwise, it defaults to 0.
- For bool(forKey:), it will return a boolean if the key exists, and false if it does not.
- When you utilize float(forKey:), it provides a float if the key exists; otherwise, it defaults to 0.0.
- Similarly, double(forKey:) returns a double if the key exists, or 0.0 if it does not.
- On the other hand, object(forKey:) returns an optional Any?, requiring conditional typecasting to your desired data type.
Q. How to set values in User defaults?
Ans. You can set values in UserDefaults by using the set(_:forKey:)
method on the UserDefaults instance.
// Access Shared Defaults Object let userDefaults = UserDefaults.standard // Set Value userDefaults.set(true, forKey: "isOnBoardingSeen")
Q. What are the types User Defaults supports ?
Ans. Below are types supported byUser Defaults
- Data
- Strings
- Numbers (NSNumber)
- Dates
- Arrays
- Dictionaries
- Booleans