Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if an integerForKey is equal to nil? Using NSUserDefaults

So far, I have a function that tries to see if someone already has a code, and if they do not already have one, then it would generate one for them. func checkID() -> Int{

    if (NSUserDefaults.standardUserDefaults().integerForKey("Code") != nil) {

    }
    else{
        var code = Int(arc4random_uniform(1000000000))
        NSUserDefaults.standardUserDefaults().setInteger(code, forKey: "Code")
    }
    return NSUserDefaults.standardUserDefaults().integerForKey("Code")
}

I get an error message when I try to to say NSUserDefaults.standardUserDefaults().integerForKey("Code") != nil

The error message I get is "Type 'Int' does not conform to protocol 'NilLiteralConvertible'"

What can I do to try to get around this? What am I doing wrong?

like image 205
Ryan Yala Avatar asked Dec 05 '22 03:12

Ryan Yala


2 Answers

The integerForKey always returns a value. If nothing's there, just 0.

So you should check like that:

if let currentValue = NSUserDefaults.standardUserDefaults().objectForKey("Code"){
    //Exists
}else{
    //Doesn't exist
}
like image 67
Christian Avatar answered Dec 30 '22 06:12

Christian


The short answer is "you can't." There's no way to tell if a zero result for integerForKey represents a stored zero value, or no value.

Christian's answer of using objectForKey (which returns an optional) and optional binding is the correct answer.

Edit:

It would be quite easy to add an extension to UserDefaults with a function that returned an Optional Int:

extension UserDefaults {
    func int(forKey key: String) -> Int? {
        return object(forKey: key) as? Int
    }
}

(I suspect that if Apple were designing the Foundations framework today, using Swift, integer(forKey:) would return an Optional(Int).)

like image 33
Duncan C Avatar answered Dec 30 '22 07:12

Duncan C