<div dir="ltr">+1 on mapValues.<div><br></div><div>DictionaryLiteral already throws an exception if it includes duplicate keys, so I'd expect mapKeys to throw an error if multiple source keys mapped to the same destination key.</div></div><div class="gmail_extra"><br><div class="gmail_quote">On Wed, Apr 13, 2016 at 11:28 AM, Miguel Angel Quinones via swift-evolution <span dir="ltr"><<a href="mailto:swift-evolution@swift.org" target="_blank">swift-evolution@swift.org</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div style="word-wrap:break-word"><div style="font-family:Helvetica,Arial;font-size:13px;color:rgba(0,0,0,1.0);margin:0px;line-height:auto">I'm +1 for adding mapValues. Very useful functionality and trivial to implement. </div><div style="font-family:Helvetica,Arial;font-size:13px;color:rgba(0,0,0,1.0);margin:0px;line-height:auto"><br></div><div><div><span class=""> > > I.e. I suggest to implement and mapKeys() also. It could be also useful in some situations.<br>> `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:<br>> <br>> extension Dictionary {<br></span>> func mapValues<u></u>(_ valueTransform: @noescape Value throws ->OutValue) rethrows ->[Key: OutValue] { … }<br>> <br>> func mapKeys<u></u>(_ keyTransform: @noescape Key throws ->OutKey) rethrows ->[OutKey: [Value]] { … }<span class=""><br>> <br>> // Possibly flatMap variants, too?<br>> }<br>> <br>> extension Dictionary where Value: Sequence {<br></span>> func reduceValues<u></u>(_ initial: OutValue, combine: @noescape (OutValue, Value.Iterator.Element) throws ->OutValue) rethrows ->[Key: OutValue] {<span class=""><br>> return mapValues { $0.reduce(initial, combine: combine) }<br>> }<br>> }<br>> <br>> Which you would end up using like this:<br>> <br>> let wordFrequencies: [String: Int] = …<br>> let firstLetterFrequencies: [Character: Int] = wordFrequencies.mapKeys { $0.characters.first! }.reduceValues(0, combine: +)<br>> <br>> --<br>> Brent Royal-Gordon<br>> Architechies<br>> <br>> <br>> <br>> <u></u><u></u><u></u></span></div></div><span class="HOEnZb"><font color="#888888"><br><div><div style="font-family:helvetica,arial;font-size:13px">-- <br>Miguel Angel Quinones<br></div></div></font></span></div><br>_______________________________________________<br>
swift-evolution mailing list<br>
<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" rel="noreferrer" target="_blank">https://lists.swift.org/mailman/listinfo/swift-evolution</a><br>
<br></blockquote></div><br></div>