swiftnsuserdefaults

Store optional bool in NSUserDefaults


I am trying to store an optional bool in NSUserDefaults where all three states are meaningful.

At the moment, it seems that if you retrieve a bool from the NSUserDefaults, if it has not been set then it returns false, which won't work for the above mentioned use case.

I don't want to user an enum as it seems overkill for what I am looking to achieve.

Is there something that I am missing here?


Solution

  • You can just take value from UserDefaults and try to cast it to Bool. If there is no value for key u get nil.

    let myBool = UserDefaults.standard.object(forKey: "BoolKey") as? Bool

    or

    let myBool = UserDefaults.standard.value(forKey: "BoolKey") as? Bool

    myBool = nil in both cases

    thanks user28434 for addition