在字典中查找值的一部分

时间:2017-01-26 22:45:45

标签: arrays swift dictionary search

我有以下字典:

["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"]

我需要执行包含某些字符的每个键。例如,如果我寻找'不',我只会得到关键字“uno”,因为“u NO Value”。如果我找'val',我会得到所有三把钥匙。

对于第二种情况,我需要获取数组中的所有键,如[“uno”]和[“uno”,“dos”,“tres”]。

我是swift的新手,但我正在为搜索构建一个虚拟应用程序,我不知道该怎么做。如果您对搜索功能有任何其他想法,我也会感激地接受它们。

3 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

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)

答案 2 :(得分:0)

我的Playground示例:

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"]