我有以下字典:
["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]
我需要做一个包含特定字符的每个键。例如,如果我寻找"no",我只会得到键"uno",因为"unoValue"。如果我找"val",我会得到所有三把钥匙。
对于第二种情况,我需要获得数组中的所有键,如["uno"]和["uno","dos","tres"]。
我是swift的新手,但我正在构建一个用于搜索的虚拟应用程序,我不知道如何做到这一点。如果您对搜索功能有任何其他想法,我也将不胜感激。
dict = {"uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"}
search_term = "Val"
list = []
for key, value in dict.items():
if search_term in value:
list.append(key)
print (list)
试试这个:
let dict = ["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]
let searchTerm = "val"
let keys = Array(
dict.keys.filter { dict[$0]!.range(of: searchTerm, options: [.caseInsensitive]) != nil }
)
print(keys)
工作原理:
dict.keys.filter
过滤字典中满足特定条件的所有关键字dict[$0]!.range(of: searchTerm, options: [.caseInsensitive]) != nil
检查包含搜索项的值Array( ... )
将其转换为字符串数组,否则为LazyFilterCollection
我的游乐场样本:
import Foundation
let dict = ["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]
let searchTerm = "val"
var result = dict.filter {
$0.value.range(of: searchTerm, options: [.caseInsensitive]) != nil
}.map{$0.key}
print(result) // ["tres", "uno", "dos"]