我有一个字典,例如:
let dict = ["1" : ["one","une"],
"2" : ["two","duex"]]
我正在使用以下代码来搜索值以获取 key 。例如,如果我搜索“one”,我将返回“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")
}
但是,这仅在我搜索完全匹配的字符串时有效。我如何才能仅通过搜索字符串的一部分来返回匹配的键。换句话说,如果我搜索“on”,它不会返回“1”。
最佳答案
你可以这样做:
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"]
在回答您的评论时,这里有一个解决方案:
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"]
关于arrays - 搜索值数组以在字典中查找键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56551580/