Saving bool to NSUserDefaults and using it in a if statement using Swift
if NSUserDefaults.standardUserDefaults().boolForKey("onoroff") == true
The above code is only check wheather the value of the key is true or not.
or
if NSUserDefaults.standardUserDefaults().objectForKey("onoroff")
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
if !NSUserDefaults.standardUserDefaults().objectForKey("onoroff"){ NSUserDefaults.standardUserDefaults().setBool(true, forKey: "onoroff")}else{ NSUserDefaults.standardUserDefaults().setBool(false, forKey: "onoroff")}
In Swift 3.0
let defaults = UserDefaults.standard
It creates the standard defaults file and configures it if it does not exist, or open it if it does.
if !UserDefaults.standard.bool(forKey: "onoroff") { UserDefaults.standard.set(true, forKey: "onoroff") } else { UserDefaults.standard.set(false, forKey: "onoroff") }
if !defaults.standard.bool(forKey: "onoroff") { defaults.standard.set(true, forKey: "onoroff") } else { defaults.standard.set(false, forKey: "onoroff") }
Thanks you @Fred for correcting the answer:-)
The accepted answer is correct. This is the way I like to do it (Swift 3.0):
struct Settings {fileprivate struct Keys { static let soundKey = "soundKey"}static var sound: Bool { set { UserDefaults.standard.set(newValue, forKey: Keys.soundKey) } get { if UserDefaults.standard.object(forKey: Keys.soundKey) == nil { // Value for sound not yet set ... Setting default ... UserDefaults.standard.set(true, forKey: Keys.soundKey) return true } return UserDefaults.standard.bool(forKey: Keys.soundKey) }}
}