Determining If Swift Dictionary Contains Key and Obtaining Any of Its Values

Determining if Swift dictionary contains key and obtaining any of its values

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
}

Check if key exists in dictionary of type [Type:Type?]

Actually your test dictionary[key] == nil can be used to check
if a key exists in a dictionary. It will not yield true if the value
is set to nil:

let dict : [String : Int?] = ["a" : 1, "b" : nil]

dict["a"] == nil // false, dict["a"] is .some(.some(1))
dict["b"] == nil // false !!, dict["b"] is .some(.none)
dict["c"] == nil // true, dict["c"] is .none

To distinguish between "key is not present in dict" and "value for key is nil" you
can do a nested optional assignment:

if let val = dict["key"] {
if let x = val {
print(x)
} else {
print("value is nil")
}
} else {
print("key is not present in dict")
}

Check if dictionary contains value in Swift

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

how to check if a key equal a value in swift dictionary?

According to the https://developer.apple.com/documentation/swift/dictionary

Every dictionary is an unordered collection of key-value pairs. You
can iterate over a dictionary using a for-in loop, decomposing each
key-value pair into the elements of a tuple.

This means you can write the following code:

let myDict = ["Item" : " Item1", "Item2" : " Item3"]
for (key, val) in myDict {
if (key == "Item2" && val == " Item3") {
print("match!") //prints match!
}
}

This is obviously kind of a "naive" approach where the values are hardcoded in the if-statement. A one-line alternative:

print(myDict.contains(where: { $0.key == "Item2" && $0.value == " Item3" })) //true

Let's say you need to check for two pairs. Then you can use KeyValuePairs which preserves the order and simply iterate:

let toFind: KeyValuePairs = [ "Item2" : " Item3",  "Itemx" : " Item4"]
for tup in toFind {
print(myDict.contains(where: { $0 == tup })) //true, false
}

If you want to follow this approach, I recommend reading about the important differences between Dictionary and KeyValuePairs https://developer.apple.com/documentation/swift/keyvaluepairs

How to find key from Dictionary having value as dictionary in Swift?

Assuming your dictionary will be of type [String: [String: Double]], you can try below code.

let mainDict: [String: [String: Double]] = ["1": ["1623699578": 1.08], "2": ["1216047930": 6.81]]
//Key for which you want the value like 1,2,3...
let key = "1"

if let valueForMainKey = mainDict[key],
let value = valueForMainKey.keys.first {
print("value:- \(value)")
}

getting the value of a selected key in a dictionary swift

You can get the code as below,

if let codeDict = self.downloadPhotosData()[action.title!] as? [String: String] {
print(codeDict["code"]!)
}

Dictionary Key Present or Not?

you can use this extension of Dictionary to check whether key is exist or not.

extension Dictionary {
func contain(_ key: Key) -> Bool {
return self[key] != nil
}
}

i.e

let dict = ["temp" : 2, "temp2" : false, 501 : "2"] as [AnyHashable : Any]

dict.contain("temp") // true

Check If Swift Dictionary Contains No Values?

There's the easy way:

dicts.values.flatten().isEmpty

But that will walk through all the lists without any shortcuts. Usually that's really not a problem. But if you want to bail out when you find a non-empty one:

func isEmptyLists(dict: [String: [String]]) -> Bool {
for list in dicts.values {
if !list.isEmpty { return false }
}
return true
}

Of course you can make this much more generic to get short-cutting and convenience:

extension SequenceType {
func allPass(passPredicate: (Generator.Element) -> Bool) -> Bool {
for x in self {
if !passPredicate(x) { return false }
}
return true
}
}

let empty = dicts.values.allPass{ $0.isEmpty }

How do I get the key at a specific index from a Dictionary in Swift?

That's because keys returns LazyMapCollection<[Key : Value], Key>, which can't be subscripted with an Int. One way to handle this is to advance the dictionary's startIndex by the integer that you wanted to subscript by, for example:

let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]

Another possible solution would be to initialize an array with keys as input, then you can use integer subscripts on the result:

let firstKey = Array(myDictionary.keys)[0] // or .first

Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.

Swift dictionary: return values for all keys containing a prefix

let dict = ["ken" : 0, "Kendall" : 1, "kenny" : 2, "Sam" : 0, "Ben" : 3]

let result = dict.filter( { $0.key.lowercased().hasPrefix("ken") } ).values


Related Topics



Leave a reply



Submit