我有一些数据模仿这样的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
闭包。我该怎么做?
答案 0 :(得分:3)
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)
}
答案 1 :(得分:2)
let adults = people.filter { person in
return person["married"] as Bool && person["age"] as Int > 20
}
答案 2 :(得分:0)
尝试:
let old = people.filter { person in
return (person["married"] as NSNumber).boolValue && (person["age"] as NSNumber).intValue > 20
}
由于您使用AnyObject,因此必须将它们用作NSNumbers
或者,您可以将声明更改为Array<Dictionary<String,Any>>
并使用:
let old = people.filter { person in
return person["married"] as Bool && person["age"] as Int > 20
}