【问题标题】:CompactMap to filter objects that have nil propertiesCompactMap 过滤具有 nil 属性的对象
【发布时间】:2019-09-16 00:35:45
【问题描述】:

如何使用 compactMap 过滤掉属性中可能的 nil 值,这样我就不必预测 nil 属性来返回对象。

目前我有

let objects: [Object] = anotherObject.array.compactMap ({
                        return Object(property: $0.property!)
 })

我想要的是一些保护声明或选项来过滤掉这些可能具有可能为 nil 的属性的对象。例如,如果 $0.property 为 nil

【问题讨论】:

    标签: arrays swift collections


    【解决方案1】:

    你可以这样做:

    let objects: [Object] = anotherObject.array.compactMap {
        return $0.property == nil ? nil : $0
    }
    

    或者使用filter:

    let objects: [Object] = anotherObject.array.filter { $0.property != nil }
    

    【讨论】:

      【解决方案2】:

      你仍然可以使用Array.compactMap

      使用 if 语句

      anotherObject.array.compactMap { object in
          if let property = object.property {
              return Object(property: property)
          }
          return nil
      }
      

      带有保护声明

      anotherObject.array.compactMap {
          guard let property = $0.property else { return nil }
      
          return Object(property: property)
      }
      

      三元运算符示例

      anotherObject.array.compactMap { object in
          object.property == nil ? nil : Object(property: object.property!)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-12
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        • 2013-07-04
        • 2015-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多