Add compactMapValues to Dictionary

How about something like this as the implementation?

extension Dictionary {
    func compactMapValues<U>(_ transform:(Dictionary.Value)throws->U?)rethrows -> [Dictionary.Key:U] {
        var result:[Key:U] = [:]
        for (k,v) in self {
            if let newValue = try transform(v) {
                result[k] = newValue
            }
        }
        return result
    }
}
1 Like