Swift - How to set initial value for NSUserDefaults

Big Green Alligator picture Big Green Alligator · Jun 15, 2016 · Viewed 31k times · Source

I have a switch called soundSwitch, I am saving the state of the button using an user default as such:

@IBAction func soundsChanged(sender: AnyObject) {
        if soundSwitch.on{
            defaults.setBool(true, forKey: "SoundActive")
            print("Sound ON")
        }else{
            defaults.setBool(false, forKey: "SoundActive")
            print("Sound OFF")
        }
    }

Currently the actual defaults value is initially false when the user first launches the application.

How do I implement the defaults to be true if the user is first launching the app and it they haven't been configured yet.

I have seen methods in Objective-C, but nothing in Swift. From what I have seen you can do it in the app delegate some how, or in a plist file. How do I do either of those ones?

Answer

Novi picture Novi · Oct 3, 2016

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")