344

I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the same dictionary.

How can one put this more elegantly in Swift?

// excerpt from method that determines if dict contains key
if let _ = dict[key] {
    return true
}
else {
    return false
}

// excerpt from method that obtains first value from dict
for (_, value) in dict {
    return value
}
4
  • You can use indexForKey if you feel it is clearer and more explicit; stackoverflow.com/a/29299943/294884
    – Fattie
    Dec 9, 2016 at 13:03
  • Very often what you want is basically: cityName:String = dict["city"] ?? "" The ?? "" here means basically "if there's no such key, return a blank".
    – Fattie
    Jan 5, 2017 at 12:09
  • Dictionary.keys.contains() is O(1) for practical purposes (O(n) is worst case.). And more readable than the alternatives here, and handles optional values correctly. See here. Sep 9 at 17:55
  • It looks like if the SwiftData 'isAutosaveEnabled` is disabled, the deleteRule does not work as it should. I disabled it and manually saved the context every time I added or edited any of the model objects and somehow the deleteRule does not apply correctly. Also the views does not update correctly. If I enable it, the view updates correctly (but I still have an issue) and the deleteRule apply as expected. Nov 2 at 19:28

8 Answers 8

577

You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}
17
  • 7
    I don't follow. I just did obtain a value (twice). What more do you want?
    – matt
    Jan 24, 2015 at 19:43
  • 1
    Be careful because dict.values is opaque. You can cycle thru it but that's all. (Okay, it's not all, but humor me.) If you want it reified to an Array, take dict.values.array.
    – matt
    Jan 24, 2015 at 19:49
  • 1
    @bubakazouba Try this: let d = ["hey":"ho"]; let s = d["hey"]; print(s) It's an Optional, just like it's always been.
    – matt
    Sep 17, 2015 at 22:34
  • 1
    @Kross That is a very profound question but therefore please ask it separately.
    – matt
    Jan 27, 2020 at 18:04
  • 1
    Just a note to use index(forKey: k) != nil if you need to deal with @Bergy's concern Oct 21, 2020 at 18:05
92

Why not simply check for dict.keys.contains(key)? Checking for dict[key] != nil will not work in cases where the value is nil. As with a dictionary [String: String?] for example.

11
  • 3
    Or instead of just writing if let val = dict[key] you can use if let val = dict[key] as? String in this case. Nov 3, 2017 at 13:37
  • 29
    This is potentially very wasteful, because (1) you call dict.keys that creates an array with all the keys, then (2) checks every key in order until you find one (or none!). I realize you are trying to address the case of a [String: String?], but would be very careful with that solution...
    – charles
    Nov 28, 2018 at 22:49
  • 3
    As @charles mentioned, this would eliminate the fast lookup benefit that using a dictionary provides so I'd advise against this one, but still definitely a valid option. Apr 5, 2019 at 5:43
  • 19
    You should never use this method, in has complexity O(n) instead of theoretical (depends on hash function implementation) O(1) of direct dictionary access.
    – Krypt
    Sep 9, 2019 at 19:25
  • 4
    @charles I don't see anywhere in the docs for keys that it says it creates an array or that contains is O(n). It says it's a view, but doesn't seem to indicate its performance characteristics. Hopefully, it doesn't make a copy and is O(1). Nov 22, 2020 at 17:09
80

The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.

If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).

if dict.keys.contains(key) {
  // contains key
} else { 
  // does not contain key
}
9
  • 12
    This is the same as Han's answer. Apr 28, 2018 at 19:43
  • 11
    Checking == nil does work, even if the dictionary has optional values. This is because the lookup result is wrapped as an Optional. On the other hand, to check if the looked up value is really nil rather than absent, you can use == .some(nil).
    – jedwidz
    Oct 4, 2018 at 15:42
  • 1
    I would add the efficiency of using this method compared to the O(1) lookup of the other methods. I believe it’s O(n) lookup May 26, 2019 at 18:16
  • 2
    @AlbertoVega-MSFT It's O(1). See also: github.com/apple/swift-evolution/blob/master/proposals/… What made you think it was O(n)?
    – Alexander
    Aug 1, 2019 at 19:18
  • 9
    The documentation for the Dictionary.Keys.contains(...) function here says it has O(n) complexity, where n is the length of the sequence. Nov 4, 2019 at 18:37
5

Looks like you got what you need from @matt, but if you want a quick way to get a value for a key, or just the first value if that key doesn’t exist:

extension Dictionary {
    func keyedOrFirstValue(key: Key) -> Value? {
        // if key not found, replace the nil with 
        // the first element of the values collection
        return self[key] ?? first(self.values)
        // note, this is still an optional (because the
        // dictionary could be empty)
    }
}

let d = ["one":"red", "two":"blue"]

d.keyedOrFirstValue("one")  // {Some "red"}
d.keyedOrFirstValue("two")  // {Some "blue"}
d.keyedOrFirstValue("three")  // {Some "red”}

Note, no guarantees what you'll actually get as the first value, it just happens in this case to return “red”.

1
  • 1
    good use of the ?? operator took my convenience solution from me, but as an extension that default value could present data insecurities or unexpected behaviors. That sounds like something a concrete subclass of Dictionary ought to employ. How often do you need the first value in case of a nil return excluding situation specific functionality? Apr 15, 2016 at 14:24
1

My solution for a cache implementation that stores optional NSAttributedString:

public static var attributedMessageTextCache    = [String: NSAttributedString?]()

    if attributedMessageTextCache.index(forKey: "key") != nil
    {
        if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
        {
            return attributedMessageText
        }
        return nil
    }

    TextChatCache.attributedMessageTextCache["key"] = .some(.none)
    return nil
0

If you want to return the value of the key you can use this extension

extension Dictionary {
    func containsKey(_ key: Key) -> Value? {
        if let index = index(forKey: key){
            return self.values[index]
        }
        return nil
    }
}
1
  • How is this any different from doing dictionary["key"]?
    – Zun
    Aug 18, 2022 at 8:36
-1

If you are dealing with dictionary that may contain nil value for a key then you can check existence of key by:

dictionay.index(forKey: item.key) != nil

For getting first value in dictionary:

dictionay.first?.value // optional since dictionary might be empty
-2
if dictionayTemp["quantity"] != nil
    {

  //write your code
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.