2017-04-21 23 views
0

如何使用Swift函数(如过滤器)优化代码? 我想要做的是我需要找到一个特定的密钥,如果存在的话,无论该密钥的值是在下面的数组中?使用过滤器查找数组中的键Swift 3

下面的方法适用于我,但我认为有一些更好的方法来做到这一点。

let arrDic = [["Key1": "yes"], ["Key2": "no"], ["Key3": "yes"], ["Key4": "Option1, Option2"], ["Key5": "OC1_OPTIONB"], ["Key6": "H1_OPTIONA"]] 

for dict in arrDic { 
    if dict["Key1"] != nil { 
     print(true) 
     break 
    } 
} 
+0

比较http://stackoverflow.com/q/29679486/2976878 – Hamish

+0

@Hamish谢谢你,这就是我一直在寻找。 –

+0

适用于你的情况:'if arrDic.contains(其中:{$ 0 [“Key1”]!= nil})' –

回答

0
let arrDic = [["Key1": "yes"], ["Key2": "no"], ["Key3": "yes"], ["Key4": "Option1, Option2"], ["Key5": "OC1_OPTIONB"], ["Key6": "H1_OPTIONA"]] 

let result = arrDic.filter { $0["Key1"] != nil }.first 

对不起,没注意的意图,然后添加

print(result != nil) 

,甚至更短的

let isPresent = arrDic.filter { $0["Key1"] != nil }.isEmpty 

甚至

let isPresent = arrDic.contains { $0["Key1"] != nil } 
0

您可以 搜索使用自定义的匹配与contains项目:

if arrDic.contains(where: {(dict) -> Bool in 
    return dict["Key1"] != nil 
}) { 
    print(true) 
}