2014-06-19 83 views
1

的数组我有一些数据,嘲笑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] 
] 

我想遍历这个数据并返回一个只包含结婚的人上面一个二十岁的结果。我该怎么做呢?我试着开始这样的:

var adults:Array = [] 

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

但后来就死在如何进行。我也想用一个map闭包。我将如何做到这一点?

回答

2
let adults = people.filter { person in 
    return person["married"] as Bool && person["age"] as Int > 20 
} 
+0

错误我得到的是:'无法找到接受提供参数的'下标'的重载' –

+0

您需要在'people'的声明中将'AnyObject'更改为'Any'。 –

+0

是的,这是我第一次尝试Rob,但它未能编译“Playground执行失败:错误::10:3​​8:错误:无法找到接受提供参数的'subscript'的重载 return Bool && person [“age”]作为Int> 20 “ –

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) 
} 
+0

我的错误,我得到的是'无法找到接受所提供参数的'过滤器'的重载 - 这是启动过滤器的行 –

+0

我只在测试版1上测试过它, y在beta2中略有变化,这会迫使一个小小的变化。 –

+0

我在beta2操场上试过了,它立即崩溃了Xcode。但它看起来对我有效。 –

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 
} 
+0

还要注意,既然你嘲笑现有的API,你可能会检索JSON结果是得到解析成NSArrays,NSDictionaries和NSNumbers,所以通过NSNumber投射将是您的长期解决方案。 –

0

With Swift 4,Array,与任何符合序列协议的类型一样,具有称为filter(_:)的方法。 filter(_:)有如下声明:

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element] 

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.


以下游乐场代码展示了如何使用filter(_:)为了与所需的谓词来过滤数组:

let people: [[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 filterClosure = { (personDictionary: [String : Any]) -> Bool in 
    guard let marriedBool = personDictionary["married"] as? Bool, let validAgeBool = personDictionary["age"] as? Int else { return false } 
    return marriedBool == true && validAgeBool > 20 
} 

let filteredPeople = people.filter(filterClosure) 
print(filteredPeople) 

/* 
prints: 
[["name": "harry", "age": 28, "employed": true, "married": true]] 
*/