#76: compactMapValues for Dictionaries

When you are transforming the values of a dictionary and some results should be discarded, compactMapValues is perfect.

let raw = ["a": "1", "b": "x", "c": "3"]
let parsed = raw.compactMapValues(Int.init)
// ["a": 1, "c": 3]

It keeps the original keys, transforms each value and drops the entries where the transform returns nil.

That is much cleaner than manually filtering and rebuilding the dictionary yourself.


I'm also on Twitter and GitHub.

Subscribe via RSS.