I'm trying to check if the a user default exists, seen below:
func userAlreadyExist() -> Bool {
var userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
if userDefaults.objectForKey(kUSERID) {
return true
}
return false
}
However, no mater what it will always return true even when the object doesn't exist yet? Is this the right way for checking existence ?
Astun has a great answer. See below for the Swift 3 version.
I copy/pasted your code but Xcode 6.1.1 was throwing some errors my way, it ended up looking like this and it works like a charm. Thanks!
This is essentially the same as suggested in other answers but in a more convenient way (Swift 3+):
Simple Code to check whether value stored in UserDefault.
for swift 3.2
Yes this is right way to check the
optional
havenil
or any valueobjectForKey
method returnsAnyObject?
which isImplicit optional
.So if
userDefaults.objectForKey(kUSERID)
have any value than it evaluates totrue
. ifuserDefaults.objectForKey(kUSERID)
hasnil
value than it evaluates tofalse
.From swift programming guide
Now there is a bug in simulators than after setting key in
userDefaults
they always remain set no matter you delete your app.You need to reset simulator.Reset your Simulator check this method before setting key in
userDefaults
or remove keyuserDefaults.removeObjectForKey(kUSERID)
fromuserDefaults
and it will returnNO
.On devices it is resolved iniOS8 beta4
.