[swift-evolution] [Proposal] mapValues
Brent Royal-Gordon
brent at architechies.com
Wed Apr 13 05:15:46 CDT 2016
> I.e. I suggest to implement and mapKeys() also. It could be also useful in some situations.
`mapKeys` is much more dangerous, because you could end up mapping many values into a single key. You kind of need to combine the values somehow. Perhaps:
extension Dictionary {
func mapValues<OutValue>(_ valueTransform: @noescape Value throws -> OutValue) rethrows -> [Key: OutValue] { … }
func mapKeys<OutKey: Hashable>(_ keyTransform: @noescape Key throws -> OutKey) rethrows -> [OutKey: [Value]] { … }
// Possibly flatMap variants, too?
}
extension Dictionary where Value: Sequence {
func reduceValues<OutValue>(_ initial: OutValue, combine: @noescape (OutValue, Value.Iterator.Element) throws -> OutValue) rethrows -> [Key: OutValue] {
return mapValues { $0.reduce(initial, combine: combine) }
}
}
Which you would end up using like this:
let wordFrequencies: [String: Int] = …
let firstLetterFrequencies: [Character: Int] = wordFrequencies.mapKeys { $0.characters.first! }.reduceValues(0, combine: +)
--
Brent Royal-Gordon
Architechies
More information about the swift-evolution
mailing list