Add constraints to generic parameters in extension

后端 未结 2 1314
深忆病人
深忆病人 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() -> [Key: Wrapped] where Value == Optional {
             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() -> [Key: Wrapped] where Value == Optional {
            var result: [Key: Wrapped] = [:]
            for (key, value) in self {
                guard let value = value else { continue }
                result[key] = value
            }
            return result
        }
    }
    

提交回复
热议问题