Swift - How to set initial value for NSUserDefaults
Swift 3 syntax example
Register a boolean default value:
UserDefaults.standard.register(defaults: ["SoundActive" : true])
And to get the value:
UserDefaults.standard.bool(forKey: "SoundActive")
Sidenote: Although the above code will return true, note that the value isn't actually written to disk until you set it:
UserDefaults.standard.set(true, forKey: "SoundActive")
Add this to your didFinishLaunchingWithOptions
method from the AppDelegate. As some others pointed out try not to abuse by putting everything in this method.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /// Here you can give default values to your UserDefault keys UserDefaults.standard.register(defaults: [ "SoundActive": true, "someOtherKey": "Some Message" ])}
Swift 4
I prefer to implement a function similar to UserDefaults.string(forKey: )
which returns nil
if the value is not set. Combined with the ?? operator, you don't need to have any default values written to disk unless you explicitly set them later.
extension UserDefaults { public func optionalInt(forKey defaultName: String) -> Int? { let defaults = self if let value = defaults.value(forKey: defaultName) { return value as? Int } return nil } public func optionalBool(forKey defaultName: String) -> Bool? { let defaults = self if let value = defaults.value(forKey: defaultName) { return value as? Bool } return nil }}
Then you can retrieve your default values as follows
let defaults = UserDefaults.standardlet userName = defaults.string(forKey: "Username") ?? "Happy"let userAge = defaults.optionalInt(forKey: "Age") ?? 21let isSmart = defaults.optionalBool(forKey: "Smart") ?? true