Adeline Adeline - 2 months ago 24x
Swift Question

Find one key containing string in swift dictionary

I have a

dictionary. I would like to get the value associated with any key containing the string "S". Order does not matter.

This is dead easy : just get all the keys, iterate, return the first matching the condition.

HOWEVER, I would like to do that using a swift-like elegant approach. Something using a
functions. And that's where I get lost...


Since you are only interested in any matching value, you can use the indexOf() method to find the first matching dictionary entry. This works because a dictionary is a collection of key/value pairs:

let dict = ["foo": "bar", "PQRS": "baz"]
let searchTerm = "s"

if let index = dict.indexOf({ (key, _) in
    // Return true if key contains the search string, case insensitive:
    key.rangeOfString(searchTerm, options: .CaseInsensitiveSearch) != nil
}) {
    // `index` is a "dictionary index" which can be used directly to obtain the corresponding entry:
    let value = dict[index].1
} else {
    print("no match")

(The advantage is that the search stops as soon as a matching key is found, instead of computing an array of all matching keys first.)

In Swift 3 you can use first(where:) to find the first matching element, this saves one dictionary lookup:

if let entry = dict.first(where: {
    (key, _) in
    key.range(of: searchTerm, options: .caseInsensitive) != nil
}) {
} else {
    print("no match")