2014-06-19 133 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]] 
*/