Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 301
Greg Peckory Avatar asked Jul 17 '15 06:07

Greg Peckory


1 Answers

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

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

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

Swift 3

let userDefaults = UserDefaults.standard
let appDefaults: [String:Any] = ["someBooleanValue" : true, 
                                 "someStringValue" : "foo"]
userDefaults.register(defaults: appDefaults)
like image 192
vadian Avatar answered Oct 30 '22 16:10

vadian