Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with non-optional values in NSUserDefaults in Swift

To get a value from NSUserDefaults I would do something like this:

let userDefaults = NSUserDefaults.standardUserDefaults()
if let value = userDefaults.objectForKey(key) {
    print(value)
}

However, these methods do not return optionals:

  • boolForKey (defaults to false if not set)
  • integerForKey (defaults to 0 if not set)
  • floatForKey (defaults to 0.0 if not set)
  • doubleForKey (defaults to 0.0 if not set)

In my app I want to used the saved value of an integer if it has been previously set. And if it wasn't previously set, I want to use my own default value. The problem is that 0 is a valid integer value for my app, so I have no way of knowing if 0 is a previously saved value or if it is the default unset value.

How would I deal with this?

like image 731
Suragch Avatar asked Sep 17 '25 19:09

Suragch


2 Answers

You can use objectForKey (which returns an optional) and use as? to optionally cast it to an Int.

if let myInteger = UserDefaults.standard.object(forKey: key) as? Int {
    print(myInteger)
} else {
    print("no value was set for this key")
}

The solutions for Bool, Float, and Double would work the same way.

Note:

I recommend going with the accepted answer and setting default values rather than casting a generic object if possible.

like image 170
Suragch Avatar answered Sep 20 '25 08:09

Suragch


Register the user defaults in AppDelegate, the best place is awakeFromNib or even init. You can provide custom default values for every key.

 override init()
 {
   let defaults = UserDefaults.standard
   let defaultValues = ["key1" : 12, "key2" : 12.6]
   defaults.register(defaults: defaultValues)
   super.init()
 }

Then you can read the values from everywhere always as non-optionals

let defaults = UserDefaults.standard
myVariable1 = defaults.integer(forKey: "key1")
myVariable2 = defaults.double(forKey:"key2")
like image 40
vadian Avatar answered Sep 20 '25 09:09

vadian