2017-04-21 3 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(where:{$ 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) 
} 
関連する問題