A O
A O

Reputation: 5698

Swift, Dictionary of String:String, best way to get an array of values, where the key contains a string?

I have a dictionary, like this: {"Matt":"Apple", "Calvin":"Nut", "Susie":"Pear"}

I want to check the keys of the dictionary with a string, to see if they contain that string-- and if they do, I want to add their respective value to an array

So, if the input was "a" the return would be ["Apple", "Nut"] because "Matt" and "Calvin" matched the "a"

Basically looking for some Swift tips, otherwise I was going to implement it like this:

Upvotes: 0

Views: 577

Answers (3)

Martin R
Martin R

Reputation: 539925

You can filter the dictionary, using contains() on each key, and then extract the corresponding values:

let dict = [ "Matt":"Apple", "Calvin":"Nut", "Susie":"Pear" ]
let input = "a"

let values = Array(dict.filter { $0.key.contains(input) }.values)
print(values) // ["Apple", "Nut"]

Or with flatMap() (renamed to compactMap() in Swift 4.1):

let values = dict.flatMap { $0.key.contains(input) ? $0.value : nil }
print(values) // ["Apple", "Nut"]

Here each dictionary entry is mapped to the value if the key contains the given string, and to nil otherwise. flatMap() then returns an array with the non-nil values.

Upvotes: 1

Rashwan L
Rashwan L

Reputation: 38833

Do it like this:

let dict = ["Matt":"Apple", "Calvin":"Nut", "Susie":"Pear"]
let containsA = dict.filter({ $0.key.lowercased().contains("a") }).map({ $0.value })

Output:

["Apple", "Nut"]

Upvotes: 1

Sulthan
Sulthan

Reputation: 130112

Simply using a filter over the dictionary:

let dict: [String: String] = ["Matt": "Apple", "Calvin": "Nut", "Susie": "Pear"]

func findValuesMatching(search: String, in dict: [String: String]) -> [String] {
    return dict
        .filter { (key, value) in
            return key.range(of: search) != nil
        }.map { (key, value) in
            return value
        }
}

print(findValuesMatching(search: "a", in: dict))

Upvotes: 1

Related Questions