Equivalent way for doing this using Swift arrays

Suppose I have an array of NSDictionaries and each dictionary contains a key called "selected" that is a boolean stored as NSNumber.

If I want to know how many of these dictionaries have selected = true, I can do this:

let count = array!.valueForKeyPath("@sum.selected")?.integerValue

but this will work for an NSArray of NSDictionaries. What about for a swift array of swift dictionaries like this

let dict1 = ["name": "Toronto Pearson1", "selected": false]
let dict2 = ["name": "Toronto Pearson2", "selected": true]
let dict3 = ["name": "Toronto Pearson3", "selected": true]

let array = [dict1, dict2, dict3]

OK, I can enumerate the array and count how many selected fields are true but I ask: is there a convenience method for doing that with Swift arrays like the @"sum.selected" on NSArrays?

Answers


You can use filter and count in swift

   let dict1 = ["name": "Toronto Pearson1", "selected": false]
    let dict2 = ["name": "Toronto Pearson2", "selected": true]
    let dict3 = ["name": "Toronto Pearson3", "selected": true]

    let array = [dict1, dict2, dict3]
    //Swift 1.2
    let result = count(filter(array){$0["selected"] == true})
    //Swift 2.0
    let result2 = array.filter{$0["selected"] == true}.count
    println(result)//2

Need Your Help

Optimize slow search algorithm - javascript, JSON and localstorage

javascript json performance search local-storage

I'm building a guestlist app for my company using PHP, Javascript/jQuery/Ajax, JSON and localstorage. It will be used on smartphones: primarily Iphone 4. I'm using localstorage as my cache since the

How to convert every time zone in GMT +5.30?

objective-c iphone-sdk-3.0 timezone nsdate

I am creating an application. I am running a countdown timer and saving time into a database by converting time into a floating point value (double). Suppose I start the timer at 2.00 PM and set the