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")
}
}
You need to use filter on the array of dictionaries to get the dictionaries, where OptionId
is 0, then use flatMap
to get the corresponding non-optional QuestionId
s.
let questionsDict: [[String:Any]] = [["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 filtered = questionsDict.filter{($0["OptionId"] as? Int) == 0}.flatMap{$0["QuestionId"] as? Int} //contains 201,200,199
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]
尝试这个:
arr.filter {return $0["OptionId"] == 0}.flatMap {return $0["QuestionId"]}return $0["QuestionId"]}
You can use filter as follows:
let searchPredicate = NSPredicate(format: "OptionId == %@",NSNumber.init(value: 0))
let filteredArray = arrayofDict.filter { searchPredicate.evaluate(with: $0) };
let result = filteredArray.flatMap{$0["QuestionId"]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.