Lucas Azzopardi
Lucas Azzopardi

Reputation: 1181

Search an array of values to find the key in a Dictionary

I have a Dictionary such as:

let dict = ["1" : ["one","une"],
            "2" : ["two","duex"]]

I am using the following code to search through values in order to get the key. For example if I search "one" I will get back "1".

let searchIndex = dict.firstIndex(where: { $0.value.contains("one") })

if let index = searchIndex {
  print("Return: \(dict[index].key)") // prints "1"    
} else {
  print("Could not find")
}

However, this only works if I search for the exact matching string. How would I be able to return matching Keys by only searching for part of the String. In other words, if I search "on", it does not return "1".

Upvotes: 1

Views: 215

Answers (3)

ielyamani
ielyamani

Reputation: 18591

You could do it this way:

let dict = ["1" : ["one","une"],
            "2" : ["two","deux"],
            "11": ["eleven, onze"]]

let searchText = "on"

let goodKeys = dict.keys.filter { key in
    dict[key]!.contains { word in
        return word.contains(searchText)
    }
}

print(goodKeys)     //["1", "11"]

In answer to your comment, here is a solution:

let searchText = "one une"
let components = searchText.components(separatedBy: " ")

let goodKeys = dict.keys.filter { key in
    dict[key]!.contains { word in
        return components.contains { component in
            word.contains(component)
        }
    }
}

print(goodKeys)     //["1"] 

Upvotes: 1

vadian
vadian

Reputation: 285260

There is also a contains(where: API

let dict = ["1" : ["one","une"],
            "2" : ["two","duex"]]

let searchIndex = dict.firstIndex(where: { $0.value.contains(where: {$0.hasPrefix("on")})})

if let index = searchIndex {
    print("Return: \(dict[index].key)") // prints "1"
} else {
    print("Could not find")
}

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 52088

Maybe not the shortest solution but it seems to work fine

var foundKey: String?
dict.contains(where: { key, value in
   if value.contains(where: {$0.contains("on") }) {
       foundKey = key
       return true
    }
    return false
})

if let key = foundKey {
    print("Return: \(key)") 
} else {
    print("Could not find")
}

To handle multiplie possible matches

var foundKeys = [String]()
dict.contains(where: { key, value in
    if value.contains(where: {$0.contains("o") }) {
        foundKeys.append(key)
    }
    return false
})

if foundKeys.count > 0 {
    print("Return: \(foundKeys)")
} else {
    print("Could not find")
}

Upvotes: 1

Related Questions