Eri-Sklii
Eri-Sklii

Reputation: 589

Check if NSUserDefaults key exists

In my application, I am saving a key using this code:

func saveKey(){
        var xmineSpillere = mineSpillere
        var defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(xmineSpillere, forKey: "YourKey")
    }

But how can I check if the key exists? I want the code something like this:

if key("YourKey") exists {
    println("key exists")
}
else {
    println("does not exist")
}

How can I do something like this in Swift?

Upvotes: 9

Views: 20040

Answers (5)

Luc-Olivier
Luc-Olivier

Reputation: 3973

Here's an integrated solution for conditional binding as an extension of UserDefaults that return an optional rather than a default values if the key doesn't exist like integer, double, float = 0, or bool = false.

Other types already returning an optional are also conveniently integrated (in the same order than the API) to have a global semantic.

extension UserDefaults {
    func valueOrNil<T>(forKey key: String) -> T? {
        guard UserDefaults.standard.object(forKey: key) != nil else { return nil }
        switch T.self {
        case is URL?.Type:
            return UserDefaults.standard.url(forKey: key) as! T?
        case is Array<Any>?.Type:
            return UserDefaults.standard.array(forKey: key) as! T?
        case is Dictionary<String, Any>?.Type:
            return UserDefaults.standard.dictionary(forKey: key) as! T?
        case is String?.Type:
            return UserDefaults.standard.string(forKey: key) as! T?
        case is [String]?.Type:
            return UserDefaults.standard.stringArray(forKey: key) as! T?
        case is Data?.Type:
            return UserDefaults.standard.data(forKey: key) as! T?
        case is Bool?.Type:
            return UserDefaults.standard.bool(forKey: key) as! T?
        case is Int?.Type:
            return UserDefaults.standard.integer(forKey: key) as! T?
        case is Float?.Type:
            return UserDefaults.standard.float(forKey: key) as! T?
        case is Double?.Type:
            return UserDefaults.standard.double(forKey: key) as! T?
        default: return nil
        }
    }
}

Example:

if let value: Int? = UserDefaults.standard.valueOrNil(forKey: "MyKey") {
    ...
} else {
    ...
}

Upvotes: 0

user7718859
user7718859

Reputation:

Adding this extension to UserDefaults will helps:

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

You can check if your key exist with:

if UserDefaults.contains(key: "YourKey") {
    print("Key exist")
} else {
   print("Does not exist")
}

Upvotes: 3

Rizwan Mehboob
Rizwan Mehboob

Reputation: 1373

Swift 3+

if let key = UserDefaults.standard.object(forKey: "Key"){
  // exist
} else {
  // not exist
}

Upvotes: 3

Victor Sigler
Victor Sigler

Reputation: 23451

First of all every time you save any to NSUserDefaults you need to call the synchronize() method to writes any modifications to the persistent domains to disk and updates all unmodified persistent domains to what is on disk.

func saveKey(){
    var xmineSpillere = mineSpillere
    var defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(xmineSpillere, forKey: "YourKey")
    defaults.synchronize()
}

The synchronize method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

Then you can reach any value in the following way:

if let key = NSUserDefaults.standardUserDefaults().objectForKey("YourKey"){
   // exist
}
else {
   // not exist
}

I hope this help you.

Upvotes: 24

Eri-Sklii
Eri-Sklii

Reputation: 589

Found out myself, code:

if (NSUserDefaults.standardUserDefaults().objectForKey("YourKey") != nil) {
            println("key exist")
        }

Upvotes: 8

Related Questions