Add constraints to generic parameters in extension

后端 未结 2 1309
深忆病人
深忆病人 2020-12-19 00:30

I have this function:

func flatten(dict: Dictionary>) -> Dictionary {
    v         


        
相关标签:
2条回答
  • 2020-12-19 00:53

    You can do it in a simpler way. This works with Swift 4:

    extension Dictionary {
        func flatten<Wrapped>() -> [Key: Wrapped] where Value == Optional<Wrapped> {
             return filter { $1 != nil }.mapValues { $0! }
        }
    }
    

    If you don't like the use of higher order functions or need compatibility with previous versions of Swift you can do this as well:

    extension Dictionary {
        func flatten<Wrapped>() -> [Key: Wrapped] where Value == Optional<Wrapped> {
            var result: [Key: Wrapped] = [:]
            for (key, value) in self {
                guard let value = value else { continue }
                result[key] = value
            }
            return result
        }
    }
    
    0 讨论(0)
  • 2020-12-19 01:02

    Try this code in the Playground:

    // make sure only `Optional` conforms to this protocol
    protocol OptionalEquivalent {
      typealias WrappedValueType
      func toOptional() -> WrappedValueType?
    }
    
    extension Optional: OptionalEquivalent {
      typealias WrappedValueType = Wrapped
    
      // just to cast `Optional<Wrapped>` to `Wrapped?`
      func toOptional() -> WrappedValueType? {
        return self
      }
    }
    
    extension Dictionary where Value: OptionalEquivalent {
      func flatten() -> Dictionary<Key, Value.WrappedValueType> {
        var result = Dictionary<Key, Value.WrappedValueType>()
        for (key, value) in self {
          guard let value = value.toOptional() else { continue }
          result[key] = value
        }
        return result
      }
    }
    
    let a: [String: String?] = ["a": "a", "b": nil, "c": "c", "d": nil]
    a.flatten() //["a": "a", "c": "c"]
    

    Because you cannot specify an exact type in the where clause of a protocol extension, one way you may detect exactly the Optional type is to make Optional UNIQUELY conforms to a protocol (say OptionalEquivalent).

    In order to get the wrapped value type of the Optional, I defined a typealias WrappedValueType in the custom protocol OptionalEquivalent and then made an extension of Optional, assgin the Wrapped to WrappedValueType, then you can get the type in the flatten method.

    Note that the sugarCast method is just to cast the Optional<Wrapped> to Wrapped?(which is exactly the same thing), to enable the usage guard statement.

    UPDATE

    Thanks to Rob Napier 's comment I have simplified & renamed the sugarCast() method and renamed the protocol to make it more understandable.

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