Yes this is right way to check the optional have nil or any value objectForKey method returns AnyObject? which is Implicit optional.
So if userDefaults.objectForKey(kUSERID) have any value than it evaluates to true. if userDefaults.objectForKey(kUSERID) has nil value than it evaluates to false.
If Statements and Forced Unwrapping
You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to
true; if it has no value at all, it evaluates to false.
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 key userDefaults.removeObjectForKey(kUSERID) from userDefaults
and it will return NO.On devices it is resolved in iOS8 beta4.
Simple Code to check whether value stored in UserDefault.
let userdefaults = UserDefaults.standard
if let savedValue = userdefaults.string(forKey: "key"){
print("Here you will get saved value")
} else {
print("No value in Userdefault,Either you can save value here or perform other operation")
userdefaults.set("Here you can save value", forKey: "key")
}
Many of the solutions here are valid. Still, I think they solve the wrong problem.
Usually, code like this is used to check if a value is set so another default value can be used:
if isKeyPresentInUserDefaults(key: "username") {
return UserDefaults.standard.string(forKey: "username")
} else {
return "No username was set"
}
You shouldn't care if a key is set or not. There is a far more elegant approach for having default values in UserDefaults:
UserDefault.standard.register(defaults: ["username": "No username was set"])
If you run this code at app launch, subsequent calls to UserDefaults.standard.string(forKey: "username") will return the default value of "No username was set" if no value was set for the key yet.