2014-06-19 2 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

오류가 발생했습니다 :'제공된 인수를 받아들이는 'subscript'에 대한 과부하를 찾을 수 없습니다. ' –

+0

'people' 선언에서'AnyObject'를'Any'로 변경해야합니다. –

+0

그래, 내가 롭뿐만 아니라 시도한 첫 번째 일이지만 "놀이터 실행 실패 : 오류 : : 10 : 38 : 오류 : 제공된 인수를 받아들이는 'subscript'에 대한 과부하를 찾을 수 없습니다. 반환 Boo && person [ "age"]로 사람이 ""결혼했습니다. "> age> 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

:

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(_:)를 사용하는 방법을 보여 filter(_:)는 다음과 같은 선언이 있습니다 '제공된 인수를 받아들이는 'filter'에 대한 과부하를 찾을 수 없습니다. - 이것은 필터를 시작하는 행에 있습니다. –

+0

나는 베타 1에서만 이것을 테스트했습니다. ma 사소한 변경을 요구하는 베타 2에서 약간 변경되었습니다. –

+0

나는 이것을 beta2 놀이터에서 시도해 보았고 즉시 Xcode를 깨뜨렸다. 그것은 나에게 유효하게 보입니다. –

0

시도 :

: 당신이 AnyObject을 사용하기 때문에, 당신은 NSNumbers으로

그들을 사용하거나, 당신이 Array<Dictionary<String,Any>> 및 사용에 선언을 변경할 수 있습니다

let old = people.filter { person in 
    return (person["married"] as NSNumber).boolValue && (person["age"] as NSNumber).intValue > 20 
} 

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

기존 API를 조롱하고 있기 때문에 아마도 JSON 결과를 검색하고 있습니다. NSArrays, NSDictionaries 및 NSNumber에 파싱되므로 NSNumber를 통해 캐스트하면 장기적인 솔루션이됩니다. –

0

스위프트 포함 4, Array에는 시퀀스 프로토콜을 준수하는 모든 유형과 마찬가지로 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]] 
*/