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 confirmati
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)
}
}
}