过滤字典数组

时间:2016-12-14 15:28:51

标签: dictionary swift3

我有一系列词典,例如:

  partnersList = 
     [
       ["isSelected": "true", "name": "Eduardo Jokovich", "cnpj": "11123123123412"],
       ["isSelected": "false", "name": "Jucileia Bezerra", "cnpj": "11000000123412"]
       ["isSelected": "true", "name": "George Bull", "cnpj": "11000000123232"]
     ]

我需要计算“isSelected”键等于“true”的次数。

对于上面的例子,

let numberOfSelectedPartners = partnerList.someFilter{} 

应该返回:

numberOfSelectedPartners =2

在Swift 3.0中最好的方法是什么? (没有for循环)

2 个答案:

答案 0 :(得分:1)

一行代码可以解决您的问题。

let partnersList : [[String : String]] =
        [
            ["isSelected": "true", "name": "Eduardo Jokovich", "cnpj": "11123123123412"],
            ["isSelected": "false", "name": "Jucileia Bezerra", "cnpj": "11000000123412"],
            ["isSelected": "true", "name": "George Bull", "cnpj": "11000000123232"]
    ]

    let filteredArray = partnersList.filter() {

        return  $0["isSelected"]  == "true" ? true : false;
    }

答案 1 :(得分:1)

一种可能的解决方案:

let numberOfSelectedPartners = partnersList.filter { $0["isSelected"] == "true" }
.count