2017-11-28 6 views
0

나는 Core Data에서 동일한 용어를 사용하여 검색을 수행하고 URL을 구성해야하는 프로젝트를 진행하고 있습니다. DataManager 클래스에 많은 코드를 덤프하는 대신 별도의 검색어 클래스를 만들어 쿼리 요소를 저장하고 초기화시 NSCompoundPredicateURL을 생성하려고합니다.미러로 만든 사전에서 nil 값 필터링

Mirror을 사용하여 클래스의 키와 값으로 사전을 구성했습니다. 사전에서 0이 아닌 값을 필터링하려고합니다. 사이트의 다른 곳에 솔루션을 적용하는 방법을 이해하지 못합니다.

클래스의 경우에만 varsDictionary, URLNSCompoundPredicate입니다. 따라서 클래스가 초기화 될 때 사전을 채우는 메소드를 실행하고 차례로 NSCompoundPredicateURL을 설정하는 데 사용합니다.

내가 어려움을 실행 해요

는 사전에서 nil이 아닌 값을 필터링되어

func setNonNilDictionary() { 
    // get the keys for the class' properties 
    let keys = Mirror(reflecting: self).children.flatMap{$0.label} 
    // get the values for the class' properties 
    let values = Mirror(reflecting: self).children.flatMap{$0.value} 
    // zip them into a dictionary 
    var propertyDict = Dictionary(uniqueKeysWithValues: zip(keys, values)) 
    // remove the nil values 
    let filteredDict = propertyDict.filter{$0.value != nil} 
    nonNilPropertyDict = filteredDict 

    print(nonNilPropertyDict) 
} 

나는 nonNilPropertyDict를 인쇄 할 때, 여전히 **** 거기에 nil 키를 보내고 있어요. 그래서 몇 가지 다른 솔루션을 둘러 보았습니다.하지만 내가 시도한 것과 상관없이 동일한 문제가 계속 발생합니다.

무엇이 빠졌으며 어떻게 수정합니까?

여기처럼 내 클래스 모습이다 : 당신은 직접 비교할 수 없습니다

class LastSearch: NSObject { 

    var startDate: Date? 
    var endDate: Date? 
    var minMagnitude: Double? 
    var maxMagnitude: Double? 
    var minLongitude: Double? 
    var maxLongitude: Double? 
    var minLatitude: Double? 
    var maxLatitude: Double? 
    var minDepth: Double? 
    var maxDepth: Double? 

    // methods to create predicate and url reference this dictionary 
    var nonNilPropertyDict: Dictionary<String, Any>! 

    var url: URL! 
    var predicate: NSCompoundPredicate! 

    init(startDate: Date?, endDate: Date?, 
     minMagnitude: Double?, maxMagnitude: Double?, 
     minLongitude: Double?, maxLongitude: Double?, 
     minLatitude: Double?, maxLatitude: Double?, 
     minDepth: Double?, maxDepth: Double?) { 

    super.init() 

    // Dates 
    self.startDate = startDate 
    self.endDate = endDate 

    // Magnitude Values 
    self.minMagnitude = minMagnitude 
    self.maxMagnitude = maxMagnitude 

    // Geographic Coordinates 
    self.minLongitude = minLongitude 
    self.maxLongitude = maxLongitude 
    self.minLatitude = minLatitude 
    self.maxLatitude = maxLatitude 

    // Depth Values 
    self.minDepth = minDepth 
    self.maxDepth = maxDepth 

    self.setNonNilDictionary() 
    self.setURL() 
    self.setPredicate() 

    } 

    func setNonNilDictionary() { 
    let keys = Mirror(reflecting: self).children.flatMap{$0.label} 
    let values = Mirror(reflecting: self).children.flatMap{$0.value} 
    let nonNilPropertyDict = Dictionary(uniqueKeysWithValues: zip(keys, values)) 

    print(filtered) 
    print(nonNilPropertyDict) 
    } 
} 
+0

가능한 복제가 만드는 더 좋을 것이다 (https://stackoverflow.com/questions/47393441/check-for-nil-in-dictionary) – dan

답변

1

어린이 value 때문에 유형 Any의 무기 호에 있지만 반복하면서 확신이 전무 있지 않은지 확인하기 위해 일치하는 패턴을 사용할 수 있습니다 아이들을 통해 :의

func setNonNilDictionary() {   
    var nonNilProperties = [String: Any]() 

    for child in Mirror(reflecting: self).children { 
     guard let label = child.label else { return } 

     if case Optional<Any>.some(let value) = child.value { 
      nonNilProperties[label] = value 
     } 
    } 

    nonNilPropertyDict = nonNilProperties 
} 
+0

[사전에 전무 확인] 저를 추가하는 대신에 게으른 var 그 값을 설정할 thod –

+0

고마워, 댄! 레오 모드를 구현할 수도 있습니다. – Adrian

+1

'lazy var nonNilDictionary : {String : Any} = { var dict : [String : Any] = [:] 거울에있는 자식을위한 (반영 : 자기). 어린이 { guard let key = child.label else {continue } 경우 선택 K2661에 (하자 값) = {child.value 딕셔너리 [키 = 값 }} 복귀 딕셔너리 }() ' –