NSUserDefaults has integerForKey:
, setInteger:forKey:
and stringForKey:
, but does not have setString:forKey:
.
How do you set a string to NSUserDefaults? It has setObject:forKey:
but, in Swift, String is a struct. Is it ok to use setObject:forKey:
to store a string?
Overview. The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.
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.
update: Xcode 13.2.1 • Swift 5.5.2
let string = "Hello World"
UserDefaults.standard.set(string, forKey: "string")
if let loadedString = UserDefaults.standard.string(forKey: "string") {
print(loadedString) // "Hello World"
}
The nice thing about Swift is that it allows to you to easily extend the language. You can create your own date(forKey:)
extending UserDefaults
to create an instance method as follow:
extension UserDefaults {
func date(forKey defaultName:String) -> Date? {
object(forKey: defaultName) as? Date
}
}
let userName = "Chris Lattner"
let userAddress = "1 Infinite Loop, Cupertino, CA 95014, United States"
let userDOB = DateComponents(calendar: .init(identifier: .gregorian), year: 1978).date!
UserDefaults().set(userName, forKey: "userName")
UserDefaults().set(userAddress, forKey: "userAddress")
UserDefaults().set(userDOB, forKey: "userDOB")
let loadedUserName = UserDefaults.standard.string(forKey: "userName")
let loadedUserAddress = UserDefaults.standard.string(forKey: "userAddress")
let loadedUserDOB = UserDefaults.standard.date(forKey: "userDOB")
print(loadedUserName ?? "nil") // "Chris Lattner"
print(loadedUserAddress ?? "nil") // "1 Infinite Loop, Cupertino, CA 95014, United States"
print(loadedUserDOB?.description(with: .init(identifier: "en_US")) ?? "nil") // "Sunday, January 1, 1978 at 12:00:00
Swift 3 removed .setObject
. Use .set
instead. For example:
// Create UserDefaults
let defaults = UserDefaults.standard
// Save String value to UserDefaults
// Using defaults.set(value: Any?, forKey: String)
defaults.set("Some string you want to save", forKey: "savedString")
// Get the String from UserDefaults
if let myString = defaults.string(forKey: "savedString") {
print("defaults savedString: \(myString)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With