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

后端 未结 6 1152
遇见更好的自我
遇见更好的自我 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:33

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

提交回复
热议问题