9

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Eri-Sklii
  • 549
  • 4
  • 10
  • 21

5 Answers5

24

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.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
  • I have a question Victor. The "key" i have saves data from UITableView, so how can i save it as array, and how can i read it as an array? When reading the key as array, i want to put it as a "var mineSpillere". – Eri-Sklii Jul 23 '15 at 22:35
  • Try this http://stackoverflow.com/questions/25179668/how-to-save-and-read-array-of-array-in-nsuserdefaults-in-swift – Victor Sigler Jul 23 '15 at 22:36
  • The value is in memory and can be retrieved even if you don't call `synchronize`. – jscs Dec 09 '16 at 13:36
8

Found out myself, code:

if (NSUserDefaults.standardUserDefaults().objectForKey("YourKey") != nil) {
            println("key exist")
        }
Eri-Sklii
  • 549
  • 4
  • 10
  • 21
3

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")
}
2

Swift 3+

if let key = UserDefaults.standard.object(forKey: "Key"){
  // exist
} else {
  // not exist
}
Striped
  • 2,544
  • 3
  • 25
  • 31
Rizwan Mehboob
  • 1,333
  • 17
  • 19
0

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 {
    ...
}
Luc-Olivier
  • 3,715
  • 2
  • 29
  • 29