Ios 使用Swift数组执行此操作的等效方法
假设我有一个Ios 使用Swift数组执行此操作的等效方法,ios,iphone,macos,swift,swift2,Ios,Iphone,Macos,Swift,Swift2,假设我有一个nsdictionary数组,每个字典都包含一个名为“selected”的键,该键是一个布尔值,存储为NSNumber 如果我想知道这些字典中有多少个选择了selected=true,我可以这样做: let count = array!.valueForKeyPath("@sum.selected")?.integerValue 但这将适用于nsdirectories的NSArray。像这样的一系列快速字典怎么样 let dict1 = ["name": "Toronto Pear
nsdictionary
数组,每个字典都包含一个名为“selected”的键,该键是一个布尔值,存储为NSNumber
如果我想知道这些字典中有多少个选择了selected=true
,我可以这样做:
let count = array!.valueForKeyPath("@sum.selected")?.integerValue
但这将适用于nsdirectories
的NSArray
。像这样的一系列快速字典怎么样
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“
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
swift 2出现以下错误:计数不可用:访问集合的计数属性我尚未更新到swift 2.0。我更新了答案。从错误中,您可以使用
filterArray.count
访问结果wift 2-filterArray行上的错误:filter不可用调用序列上的filter()方法数组后缺少一些括号。filterarray.filter(
但现在它正在工作。感谢您的评论,我更新了答案以澄清问题