Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift integerForKey: If the specified key does not exist, this method returns 0 [duplicate]

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?

like image 713
Eric Conner Avatar asked Dec 20 '25 23:12

Eric Conner


1 Answers

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
    }
}
like image 87
Christian Avatar answered Dec 23 '25 13:12

Christian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!