Greg Peckory Greg Peckory - 1 year ago 123
Swift Question

Changing default value of User Default boolean Swift

I have the code:

let userDefaults = NSUserDefaults.standardUserDefaults()

if let branchcheck = userDefaults.boolForKey("someBooleanValue") as Bool? {

println("found boolean as \(branchcheck)")


This is grand, only when nothing has been added to user defaults this automatically returns 'false'.

I want all settings to be 'true' by default.

How is this accomplished?

Answer Source

According NSUserDefaults/AccessingPreferenceValues Apple recommends to register all default values, for example

let userDefaults = NSUserDefaults.standardUserDefaults()
let appDefaults = ["someBooleanValue" : true]

this procedure does not write anything in the preference file, but those values are defined as the default values for the appropriate keys

For Swift 3

  let userDefaults = UserDefaults.standard
  let appDefaults: [String:Any] = ["someBooleanValue" : true, 
                                   "someStringValue" : "quack"]
  userDefaults.register(defaults: appDefaults)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download