Since you are only interested in the corresponding value, you can use the indexOf() method to find the first dictionary match. This works because a dictionary is a collection of key / value pairs.
Swift 2:
let dict = ["foo": "bar", "PQRS": "baz"] let searchTerm = "S" if let index = dict.indexOf({ (key, _) in key.containsString(searchTerm) }) { let value = dict[index].1 print(value) } else { print("no match") }
As soon as the corresponding key is found, the predicate returns true and the enumeration stops. index is a "dictionary index" that can be used directly to get the corresponding entry in the dictionary.
To search for a case-insensitive keyword, replace the predicate with
{ (key, _) in key.rangeOfString(searchTerm, options: .CaseInsensitiveSearch) != nil }
In Swift 3, you can use first(where:) to find the first match of an element, this saves one search in the dictionary:
if let entry = dict.first(where: { (key, _) in key.contains(searchTerm) }) { print(entry.value) } else { print("no match") }
To search for a case-insensitive keyword, replace the predicate with
{ (key, _) in key.range(of: searchTerm, options: .caseInsensitive) != nil }
Martin r
source share