+1 for this. Highly useful method and imo should be implemented for Dictionary.

And what if we need to transform the key?
For ex. we have
var d = ["1" : "abc", "2" : "def"]
we could have such method:
d.mapKeys {k,v -> Int in Int(k)! }
to get:
[2: "abc", 1: "def"]

I.e. I suggest to implement and mapKeys() also. It could be also useful in some situations.

On 13.04.2016 9:41, Jonathan Hull via swift-evolution wrote:
I would really like to see something like the following added to the
standard library:

extensionDictionary{


func mapValues<U>(transform:(Key,Value)->U)->[Key:U] {
var output:[Key:U] = [:]
for (k,v) in self {
             output[k] = transform(k,v)
         }
return output
     }


}

It comes up enough that I have had to add it to pretty much every one of my
projects.  I also don’t feel comfortable adding it to my frameworks, since
I figure a lot of people are also adding something like this to their
projects, and I don’t want to cause a conflict with their version.  Prime
candidate for the standard library.

I like calling it ‘mapValues' as opposed to providing an override for map,
since it makes the specific behavior more clear.  I would expect ‘map' to
possibly map the keys as well (though there are issues where the new keys
overlap).  I suppose you could just have a bunch of overrides for map if
the compiler becomes good enough at differentiating return types:
(Value)->(Value), (Key,Value)->Value, (Key, Value)->(Key,Value)

Thanks,
Jon


_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to