使用 Swift 数组执行此操作的等效方法
Equivalent way for doing this using Swift arrays
假设我有一个 NSDictionaries
数组,每个字典都包含一个名为 "selected" 的键,它是一个存储为 NSNumber
.
的布尔值
如果我想知道有多少本词典有selected = true
,我可以这样做:
let count = array!.valueForKeyPath("@sum.selected")?.integerValue
但这适用于 NSArray
的 NSDictionaries
。像这样 swift 的 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 数组(如 NSArrays 上的 @"sum.selected")来做到这一点?
您可以在 swift
中使用 filter
和 count
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){[=10=]["selected"] == true})
//Swift 2.0
let result2 = array.filter{[=10=]["selected"] == true}.count
println(result)//2
假设我有一个 NSDictionaries
数组,每个字典都包含一个名为 "selected" 的键,它是一个存储为 NSNumber
.
如果我想知道有多少本词典有selected = true
,我可以这样做:
let count = array!.valueForKeyPath("@sum.selected")?.integerValue
但这适用于 NSArray
的 NSDictionaries
。像这样 swift 的 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 数组(如 NSArrays 上的 @"sum.selected")来做到这一点?
您可以在 swift
中使用filter
和 count
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){[=10=]["selected"] == true})
//Swift 2.0
let result2 = array.filter{[=10=]["selected"] == true}.count
println(result)//2