Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dictionary values swift

I have an array of dictionaries of type

[["OptionId": 824, "QuestionId": 208],
["OptionId": 810, "QuestionId": 205],
["OptionId": 1017, "QuestionId": 257],
["OptionId": 0, "QuestionId": 201],
["OptionId": 0, "QuestionId": 199],
["OptionId": 0, "QuestionId": 200]]

I have iterated through these values and extracted the dictionaries values as

["OptionId": 824, "QuestionId": 208]
["OptionId": 810, "QuestionId": 205]
["OptionId": 1017, "QuestionId": 257]
["OptionId": 0, "QuestionId": 201]
["OptionId": 0, "QuestionId": 199]
["OptionId": 0, "QuestionId": 200]

Now, I want to get the "QuestionId" for all those "OptionId" which are 0. How can I compare the dictionary key-value to zero? Thanks in advance.

This is what I have tried so far:

for dictionary in arrayofDict {
    print(dictionary)
    if (dictionary["OptionId"] == 0) {
        print("option not selected")
    }
} 
like image 954
Dyana Avatar asked May 31 '26 20:05

Dyana


1 Answers

A "filter + map" operation can be done with a single flatMap call (avoiding the creation of an intermediate array). In your case:

let arrayofDict = [["OptionId": 824, "QuestionId": 208],
                 ["OptionId": 810, "QuestionId": 205],
                 ["OptionId": 1017, "QuestionId": 257],
                 ["OptionId": 0, "QuestionId": 201],
                 ["OptionId": 0, "QuestionId": 199],
                 ["OptionId": 0, "QuestionId": 200]]

let notSelected = arrayofDict.flatMap { $0["OptionId"] == 0 ? $0["QuestionId"] : nil }

print(notSelected) // [201, 199, 200]
like image 102
Martin R Avatar answered Jun 03 '26 13:06

Martin R