我正在开展一个项目,我需要在Core Data
中使用相同的字词执行搜索,并构建URL
。我试图创建一个单独的搜索术语类,而不是在我的DataManager类中转储一堆代码,它将存储查询的元素,并在初始化时构造NSCompoundPredicate
和URL
。
我正在使用Mirror
来构造一个包含该类的键和值的字典。我试图从字典中过滤出非零值。我不明白如何在网站的其他地方应用解决方案来解决我的问题。
该类唯一的非可选vars
是Dictionary
,URL
和NSCompoundPredicate
。因此,当初始化类时,我会运行一个方法来填充字典,而该字典又用于设置NSCompoundPredicate
和URL
的设置。
我遇到困难的地方是从字典中过滤出非零值:
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
个键。我已经在SO上查看了几个不同的解决方案,但无论我尝试什么,我都会遇到同样的问题。
我缺少什么,我该如何解决?
这是我班级的样子:
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 :(得分:1)
您无法直接将孩子的config[:dates].split(",").all? { |x| is_date_valid?(x)}
与nil进行比较,因为它类型为value
,但您可以使用模式匹配来确保它们不是迭代孩子:
Any