1

How can I optimise code using Swift functions like the filter? What I want to do is I need to find a particular key if present no matter what value of that key is in the below array?

Below method works fine for me but I think there is some better way to do it.

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
    }
}
Hamish
  • 78,605
  • 19
  • 187
  • 280
Parth Adroja
  • 13,198
  • 5
  • 37
  • 71

2 Answers2

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

I'm sorry, didn't notice an intentions, add then

print(result != nil)

or even shorter

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

or even

let isPresent = arrDic.contains { $0["Key1"] != nil }
Vladyslav Zavalykhatko
  • 15,202
  • 8
  • 65
  • 100
0

You can search for an item using custom matching with contains:

if arrDic.contains(where: {(dict) -> Bool in
    return dict["Key1"] != nil
}) {
    print(true)
}
Oskar
  • 3,625
  • 2
  • 29
  • 37