나는 Core Data
에서 동일한 용어를 사용하여 검색을 수행하고 URL
을 구성해야하는 프로젝트를 진행하고 있습니다. DataManager 클래스에 많은 코드를 덤프하는 대신 별도의 검색어 클래스를 만들어 쿼리 요소를 저장하고 초기화시 NSCompoundPredicate
및 URL
을 생성하려고합니다.미러로 만든 사전에서 nil 값 필터링
Mirror
을 사용하여 클래스의 키와 값으로 사전을 구성했습니다. 사전에서 0이 아닌 값을 필터링하려고합니다. 사이트의 다른 곳에 솔루션을 적용하는 방법을 이해하지 못합니다.
클래스의 경우에만 vars
은 Dictionary
, URL
및 NSCompoundPredicate
입니다. 따라서 클래스가 초기화 될 때 사전을 채우는 메소드를 실행하고 차례로 NSCompoundPredicate
및 URL
을 설정하는 데 사용합니다.
내가 어려움을 실행 해요
는 사전에서 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)
}
}
가능한 복제가 만드는 더 좋을 것이다 (https://stackoverflow.com/questions/47393441/check-for-nil-in-dictionary) – dan