gpt4 book ai didi

arrays - 搜索值数组以在字典中查找键

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:22 25 4
gpt4 key购买 nike

我有一个字典,例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com