Marcelo Gracietti
Marcelo Gracietti

Reputation: 3131

Filtering Array of Dictionaries

I have an array of dictionaries such as:

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

And I need to count the number of times where the key "isSelected" is equal to "true".

For the example above,

let numberOfSelectedPartners = partnerList.someFilter{} 

Should return:

numberOfSelectedPartners =2

What's the best way to do it in Swift 3.0? (without for loops)

Upvotes: 0

Views: 62

Answers (2)

shallowThought
shallowThought

Reputation: 19602

One possible solution:

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

Upvotes: 1

junaidsidhu
junaidsidhu

Reputation: 3580

one line of code can solve your problem.

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;
    }

Upvotes: 1

Related Questions