I want to store an integer in NSUserDefaults that could potentially be 0. How do I distinguish between an integer that was stored as 0 and a key that does not exist in NSUserDefaults?
According to the NSUserDefaults docs integerForKey returns 0 if the key did not exist in NSUserDefaults. So, my question is: how do I distinguish between a nonexistent key and a key I've stored as 0?
You can check by using the objectForKey method because this method doesn't automatically returns 0 but returns nil, if the key doesn't exist:
if let yourInteger = NSUserDefaults.standardUserDefaults().objectForKey("yourKey"){
//Key exists
}
You could create an extension for your NSUserDefaults to check:
extension NSUserDefaults {
func hasKey(key: String) -> Bool {
return objectForKey(key) != nil
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With