Saving and retrieving a bool with UserDefaults

前端 未结 4 1388
醉酒成梦
醉酒成梦 2021-01-13 01:33

I\'m trying to save a bool value to UserDefaults from a UISwitch, and retrieve it in another view. However, I\'ve tried following multiple tutorials and stack answe

4条回答
  •  失恋的感觉
    2021-01-13 02:23

    As Leo mentioned in the comments bool(forKey returns a non-optional Bool. If the key does not exist false is returned.

    So it's simply

    boolValue = UserDefaults.standard.bool(forKey: "sound")
    

    Calling synchronize() as suggested in other answers is not needed. The framework updates the user defaults database periodically.

提交回复
热议问题