Search code examples
swiftnsdictionarynspredicate

Check if dictionary contains value in Swift


Just simple task. I've got a dictionary var types = [Int : String]() which inits like an empty and after some user actions it fills with data. According to emptiness or some specific data in this dictionary I enable/disable a button in UI. Check for emptiness is easy, but how to check if dictionary contains certain value? Compiler suggested me a placeholder with predicate:

types.contains(predicate: ((Int, String)) throws -> Bool>)

Solution

  • Since you only want to check for existance of a given value, you can apply the contains method for the values properties of your dictionary (given native Swift dictionary), e.g.

    var types: [Int : String] = [1: "foo", 2: "bar"]
    print(types.values.contains("foo")) // true
    

    As mentioned in @njuri: answer, making use of the values property of the dictionary can seemingly yield an overhead (I have not verified this myself) w.r.t. just checking the contains predicate directly against the value entry in the key-value tuple of each Dictionary element. Since Swift is fast, this shouldn't be an issue, however, unless you're working with a huge dictionary. Anyway, if you'd like to avoid using the values property, you could have a look at the alternatives given in the forementioned answer, or, use another alternative (Dictionary extension) as follows:

    extension Dictionary where Value: Equatable {
      func containsValue(value : Value) -> Bool {
        return self.contains { $0.1 == value }
      }
    }
    
    types.containsValue("foo") // true
    types.containsValue("baz") // false