Generic Swift Dictionary Extension for nil filtering

后端 未结 1 1088
甜味超标
甜味超标 2021-01-06 19:43

I\'m looking for a type safe, generic version of this answer.

This is the method signature I\'m looking for:

extension Dictionary where Value == Opti         


        
1条回答
  •  鱼传尺愫
    2021-01-06 20:22

    Update: As of Swift 5 this would be:

    let filtered = dict.compactMapValues { $0 }
    

    Update: As of Swift 4, you can simply do

    let filtered = dict.filter( { $0.value != nil }).mapValues( { $0! })
    

    It is currently being discussed if Dictionary should get a compactMapValues method which combines filter and mapValues.


    (Previous answer:) You can use the same "trick" as in How can I write a function that will unwrap a generic property in swift assuming it is an optional type? and Creating an extension to filter nils from an Array in Swift: define a protocol to which all optionals conform:

    protocol OptionalType {
        associatedtype Wrapped
        func intoOptional() -> Wrapped?
    }
    
    extension Optional : OptionalType {
        func intoOptional() -> Wrapped? {
            return self
        }
    }
    

    Then your dictionary extension can be defined as:

    extension Dictionary where Value: OptionalType {
        func filterNil() -> [Key: Value.Wrapped] {
            var result: [Key: Value.Wrapped] = [:]
            for (key, value) in self {
                if let unwrappedValue = value.intoOptional() {
                    result[key] = unwrappedValue
                }
            }
            return result
        }
    }
    

    Example:

    let dict = ["mail": nil, "name": "John Doe"] // Type is [String : String?]
    let filtered = dict.filterNil() // Type is [String : String]
    print(filtered) // Output: ["name": "John Doe"]
    

    0 讨论(0)
提交回复
热议问题