Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 633
Ryan Avatar asked Aug 03 '14 12:08

Ryan


4 Answers

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

func isKeyPresentInUserDefaults(key: String) -> Bool {
    return UserDefaults.standard.object(forKey: key) != nil
}
like image 58
user7248923 Avatar answered Oct 30 '22 08:10

user7248923


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!

func userAlreadyExist(kUsernameKey: String) -> Bool {
    return NSUserDefaults.standardUserDefaults().objectForKey(kUsernameKey) != nil
}

Swift 5:

if UserDefaults.standard.object(forKey: "keyName") != nil {
  //Key exists
}
like image 45
Astun Avatar answered Oct 30 '22 10:10

Astun


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.

From swift programming guide

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.

like image 21
codester Avatar answered Oct 30 '22 10:10

codester


This is essentially the same as suggested in other answers but in a more convenient way (Swift 3+):

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

usage: if UserDefaults.contains(kUSERID) { ... }

like image 16
Sir Codesalot Avatar answered Oct 30 '22 10:10

Sir Codesalot