Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to check if UserDefaults exists and if not save a chosen standard value?

I am trying to check if a UserDefaults Key exists and if not set it to a standard value of my choice, but the answers here on stack overflow didn't help me to get this working.

Essentially I have a couple of UISwitches, one is on and the rest is set to off from the beginning. Now my problem is that I don't know how to save these initial states into UserDefaults when the viewController is loaded and those keys do not exists.

This is how I tried to check if the key for the UISwitch exists and if not set it to true (because that's the state I want it to be) and then check again what the bool for the key is and set the UISwitch to it (this is essentially important when the viewController is opened another time):

func setupSwitches() {
    let defaults = UserDefaults.standard

    //check if the key exists 
    if !defaults.bool(forKey: "parallax") {
        switchParallax.setOn(true, animated: true)
    } 

    //check for the key and set the UISwitch
    if defaults.bool(forKey: "parallax") {
        switchParallax.setOn(true, animated: true)
    } else {
        switchParallax.setOn(false, animated: true)
    } 

}

When the user presses the corresponding button I set the UserDefaults key like this:

@IBAction func switchParallax_tapped(_ sender: UISwitch) {
    let defaults = UserDefaults.standard

    if sender.isOn == true {
        defaults.set(true, forKey: "parallax")
    } else {
        defaults.set(false, forKey: "parallax")
    }
}

This is obviously working, but the problem is in the first code above.

First of all I am not sure how to check if it exists and if not set it to "true" and since the function is called setupSwitches() it is runs every time the viewController is shown.

So I don't know if there is a better way (eg. because of the memory issues) to check if a key exists, if not set it to true and if it already exists get the bool from UserDefaults and set the switch to the right state.

like image 412
RjC Avatar asked Nov 30 '17 19:11

RjC


1 Answers

The problem is you can't determine exists with UserDefaults.standard.bool(forKey: key). UserDefaults.standard.object(forKey: key) returns Any? so you can use it to test for nil e.g.

extension UserDefaults {

    static func exists(key: String) -> Bool {
        return UserDefaults.standard.object(forKey: key) != nil
    }

}
like image 90
Norman Avatar answered Oct 23 '22 10:10

Norman