This is not as strongly motivated as mapValues
, and as such, does not make an appropriate addition to the standard library IMO.
In designing this API, you've made a decision: colliding keys should be silently coalesced. That isn't always the right decision. Sometimes colliding keys would indicate a programmer error and should trap. Sometimes you might need to do something else like deconflict them, or coalesce their values.
mapValues
OTOH doesn't have these issues. And while the mapValues
can be trivially composed, it has the benefit of potential optimization, since the dictionary does not have to rehash/bucket the values. That doesn't apply to mapKeys
.
p.s. if you find the reduce
version verbose, you can simplify it:
attributes.reduce(into: [:]) { result, x in
result[x.key.rawValue] = x.value
}
// or alternatively, including an assertion for duplicate keys
Dictionary(uniqueKeysWithValues: attributes.map({
(k,v) in (k.rawValue,v)
}))