The UserDefaults
class allows developers to interact with the defaults system, a simple key-value store. The defaults system is available on iOS, tvOS, macOS, iPadOS, and watchOS. The defaults database can only be used to store a predefined set of data types, strings, numbers, Date
objects, and Data
objects. It is also possible to store arrays or dictionaries of these types.
Writing or Setting a String To User Defaults
Storing a string in the user's defaults database is simple. You first obtain a reference to the shared defaults object through the standard
class property of the UserDefaults
class.
import Foundation
// Access Shared Defaults Object
let userDefaults = UserDefaults.standard
To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:)
method of the UserDefaults
class. We also need to pass a key as the second argument to the set(_:forKey:)
method because we are creating a key-value pair. Remember that the defaults system is nothing more than a key-value store.
import Foundation
// Access Shared Defaults Object
let userDefaults = UserDefaults.standard
// Write/Set Value
userDefaults.set("myString", forKey: "myKey")
Reading or Getting a String From User Defaults
To read the string from the defaults database, we invoke the string(forKey:)
method on the shared defaults object.
import Foundation
// Access Shared Defaults Object
let userDefaults = UserDefaults.standard
// Read/Get Value
let myString = userDefaults.string(forKey: "myKey")
The string(forKey:)
method returns a value of type String?
, an optional, because it is possible that the key-value pair doesn't exist in the defaults database.
You can also read the string from the user's defaults database by invoking the object(forKey:)
method. The object(forKey:)
method returns a value of type Any?
, an optional. We cast it to a String
object using the as?
operator.
import Foundation
// Access Shared Defaults Object
let userDefaults = UserDefaults.standard
// Read/Get Value
let myString = userDefaults.object(forKey: "myKey") as? String
I'm sure you agree that the string(forKey:)
method is the more elegant option and easier to read and understand. I strongly discourage you from using the as!
operator to forced cast the result of object(forKey:)
to a string. A runtime exception is thrown if the key that is passed to object(forKey:)
doesn't exist or if the result can't be cast to a String
object.
Use the exclamation mark sparingly in Swift. There's a good reason why it's an exclamation mark instead of a 🙂. You can read more about the exclamation mark on Cocoacasts.