Check if UserDefault exists - Swift

Ryan picture Ryan · Aug 3, 2014 · Viewed 65.7k times · Source

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 ?

Answer

user7248923 picture user7248923 · Dec 5, 2016

Astun has a great answer. See below for the Swift 3 version.

func isKeyPresentInUserDefaults(key: String) -> Bool {
    return UserDefaults.standard.object(forKey: key) != nil
}