arrays - 过滤字典数组

标签 arrays dictionary swift

我有一些数据模拟这样的 api 调用:

 var people:Array<Dictionary<String, AnyObject>> = [
     ["name":"harry", "age": 28, "employed": true, "married": true],
     ["name":"larry", "age": 19, "employed": true, "married": true],
     ["name":"rachel", "age": 23, "employed": false, "married": false]
 ]

我想迭代此数据并返回一个只包含 20 岁以上已婚人士的结果。我该怎么做呢?我试过这样开始:

var adults:Array = []

for person in people {
    for(key:String, value:AnyObject) in person {
        println(person["age"])
    }
}

但后来陷入了如何进行的困境。我还想使用 map 闭包。我该怎么做?

最佳答案

var people: Array<Dictionary<String, Any>> = [
    ["name":"harry", "age": 28, "employed": true, "married": true],
    ["name":"larry", "age": 19, "employed": true, "married": true],
    ["name":"rachel", "age": 23, "employed": false, "married": false]
]

let oldMarriedPeople = filter(people) { (person: Dictionary<String, Any>) -> Bool in
        let age = person["age"] as Int
        let married = person["married"] as Bool
        return age > 20 && married
}

for p in oldMarriedPeople {
    println(p)
}

关于arrays - 过滤字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312063/

相关文章:

javascript - Javascript 中变量不断变成对象而不是数组

ruby - 以 4 为增量迭代 Ruby 数组

ios - 如何向 loadRequest 添加闭包?

swift - 在 Swift Bridging Header 中获取 "file not found"错误

arrays - 从数组中获取一定数量的随机项

c - c 中的字符串作为数组

database - 通用开源分类数据库

python - 在 Python 中比较两个不同顺序的字典列表

ios - map 应用程序不工作

ios - 在 Swift 中获取设备方向