Saving bool to NSUserDefaults and using it in a if statement using Swift

后端 未结 6 1263
遇见更好的自我
遇见更好的自我 2021-02-19 21:44

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

6条回答
  •  执念已碎
    2021-02-19 22:36

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

    }

提交回复
热议问题