iosswiftnsuserdefaults

Check if UserDefault exists - Swift


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 ?


Solution

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

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