I am struggling to figure out how to do an if statement with a bool saved to NSUserDefaults using swift. I believe I know how to save the bool to NSUserDefaults but a confirmation in that would be greatly appreciated. This is the objective-c code i am trying to figure out how to use with swift.
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"onoroff"]) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"onoroff"];
}
this is what i have so far in swift...
if NSUserDefaults.standardUserDefaults().objectForKey("onoroff") != nil{
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "onoroff")
}
I think i might have figure it out. Can anyone confirm this is the correct way to save a bool to NSUserDefaults and use a if statement with it. Here it is...
if !NSUserDefaults.standardUserDefaults().boolForKey("onoroff"){
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "onoroff")
}else{ NSUserDefaults.standardUserDefaults().setBool(false, forKey: "onoroff")
}
The above code is only check wheather the value of the key is true or not.
or
The above code check wheather the value of the key is true or not as well if there is no value for the key.(Means Nothing inserted in the UserDefault of "onoroff").
EDIT
In Swift 3.0
It creates the standard defaults file and configures it if it does not exist, or open it if it does.
Thanks you @Fred for correcting the answer:-)
Swift 3
This is code for the switch, that will save true or false to UserDefaults.
Then to show the switch's saved state... on/off:
So really 1 line to set the switch's state, and 1 line to get the users saved state and set the switch properly!
The accepted answer is correct. This is the way I like to do it (Swift 3.0):
}
EDIT: