简体   繁体   English

比较字典值迅速

[英]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? 现在,我想获取所有“ OptionId”均为0的“ QuestionId”。如何将字典键值与零进行比较? 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. 您需要在字典数组上使用filter来获取字典,其中OptionId为0,然后使用flatMap来获取相应的非可选QuestionId

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). 可以通过一个flatMap调用来完成“ filter + map”操作(避免创建中间数组)。 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"]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM