【问题标题】:Equivalent way for doing this using Swift arrays使用 Swift 数组执行此操作的等效方法
【发布时间】:2015-07-19 07:14:33
【问题描述】:

假设我有一个NSDictionaries 数组,每个字典都包含一个名为“selected”的键,它是一个存储为NSNumber 的布尔值。

如果我想知道这些词典中有多少有selected = true,我可以这样做:

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

但这适用于NSArrayNSDictionaries。像这样的快速字典呢?

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"?

【问题讨论】:

    标签: ios iphone macos swift swift2


    【解决方案1】:

    你可以在swift中使用filtercount

       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 给我这个错误:count is available: access the count property on the collection
    • 我还没有更新到 Swift 2.0。我更新了答案。从错误中,您可以使用filterdArray .count 访问结果
    • swift 2 - filterdArray 行出错:过滤器不可用调用序列上的 filter() 方法
    • 您在 array.filter 之后缺少一些括号... array.filter( 但现在它正在工作。谢谢
    • 感谢您的评论,我更新了答案以使其清楚
    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2020-06-02
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多