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?
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
}
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.
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)
.)
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