我有一些数据模拟这样的 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/