从用镜像创建的字典中过滤零值



我有一个项目,我正在努力使用Core Data中的相同项并构建URL的搜索。我没有在我的datamanager类中转载一堆代码,而是尝试创建一个单独的搜索术语类,该类别将在初始化时存储查询的元素并构造NSCompoundPredicateURL

我正在使用Mirror来构造一个带有类的键和值的字典。我正在尝试从字典中滤除非nil值。我不明白如何将网站其他地方的解决方案应用于我的问题。

该类唯一的非选手varsDictionaryURLNSCompoundPredicate。因此,当班级初始化时,我运行了一种填充字典的方法,该字典又用于设置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)
  }
}

您不能直接将孩子的value与nil进行比较,因为它的类型为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
}

最新更新