In this article, we will be discussing UserDefaults in swift from scratch to the advance.
Firstly, we would explore what UserDefaults is in Swift. After that, we will discuss how we can take advantage of the UserDefaults. We will also know how the UserDefaults works internally
So let’s dive into the article.
UserDefaults in Swift Overview
Firstly, we are going to discuss how UserDefaults works internally.
UserDefaults uses the .plist file to store the data in key-value pairs.
Swift uses suites/domains to save data. Each suite has its own .plist file.
By default, every app has 8 suites which are listed below.
ADD_DOMAIN(_CFPreferencesStandardDomain(appPreferences->_appName, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost));
ADD_DOMAIN(_CFPreferencesStandardDomain(appPreferences->_appName, kCFPreferencesCurrentUser, kCFPreferencesAnyHost));
ADD_DOMAIN(_CFPreferencesStandardDomain(kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost));
ADD_DOMAIN(_CFPreferencesStandardDomain(kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost));
ADD_DOMAIN(_CFPreferencesStandardDomain(appPreferences->_appName, kCFPreferencesAnyUser, kCFPreferencesCurrentHost));
ADD_DOMAIN(_CFPreferencesStandardDomain(appPreferences->_appName, kCFPreferencesAnyUser, kCFPreferencesAnyHost));
ADD_DOMAIN(_CFPreferencesStandardDomain(kCFPreferencesAnyApplication, kCFPreferencesAnyUser, kCFPreferencesCurrentHost));
ADD_DOMAIN(_CFPreferencesStandardDomain(kCFPreferencesAnyApplication, kCFPreferencesAnyUser, kCFPreferencesAnyHost));
The suites are organized into search-list, so when we perform read/write operation the search list is initialized for the first time.
We can add as many suites as we want, and customize the UserDefaults according to our requirements.
You can define your suite as below
1 |
UserDefaults.standard.addSuite(named: "Your suite name") |
To store the values in UserDefaults CFPreferencesSetAppValue(_:_:_:) function is used. For instance, you can declare the function as
1 2 3 |
func CFPreferencesSetAppValue(_ key: CFString, _ value: CFPropertyList?, _ applicationID: CFString) |
Note: UserDefaults works best when the read operations are frequent and write operations are less.
Creating UserDefaults using Property Wrapper
1 2 3 4 5 6 7 8 9 10 |
@propertyWrapper struct UserDefault<T: PropertyListValue> { let key: Key var wrappedValue: T? { get { UserDefaults.standard.value(forKey: key.rawValue) as? T } set { UserDefaults.standard.set(newValue, forKey: key.rawValue) } } } |
The above code uses the PropertyListValue protocol.
You can create the structure for Key as below.
1 2 3 4 |
struct Key: RawRepresentable { let rawValue: String } |
After that, you can extend the Key struct for your statically defined key values.
Read, Write, Delete and Update operations for UserDefaults in Swift
You can perform Write operations as
1 2 3 4 5 6 7 8 9 10 11 |
let defaults = UserDefaults.standard defaults.set(5, forKey: "Number") defaults.set(true, forKey: "Boolean") defaults.set(CGFloat.pi, forKey: "Pi") defaults.set(Date(), forKey: "Date") let array = ["Hi", "There"] defaults.set(array, forKey: "array") let dict = ["Name": "abc", "lastName": "xyz"] defaults.set(dict, forKey: "Dictionary") |
After that, you can perform the Read operation as
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
if let name = UserDefaults.standard.string(forKey: "name") { print(name) } // getting saved string value if let number = UserDefaults.standard.integer(forKey: "Number") { print(number) } // getting saved integer value if let array = UserDefaults.standard.array(forKey: "array") { print(array) } // getting saved array value if let boolean = UserDefaults.standard.bool(forKey: "Boolean") { print(boolean) } // getting saved boolean value if let savedData = defaults.object(forKey: "user") as? Data { let decoder = JSONDecoder() if let savedUser = try? decoder.decode(User.self, from: savedUserData) { print("Saved user: \(savedUser)") } }// getting saved custom data value |
Similarly, We can remove or delete the saved data.
1 |
UserDefaults.standard.removeObject(forKey: "user") |
To update the value for a key in UserDefault just set another value in the same key as the Write operation.
Conclusion
To go more deep inside the UserDefaults you can refer to the below link
Please read out more interesting articles here.