[swift-users] Mapping a Dictionary to a Dictionary?
Lou Zell
lzell11 at gmail.com
Mon Aug 29 21:31:21 CDT 2016
>
> I’m talking about a function that does for Dictionaries what map() does
> for Arrays: it transforms every key and value in the input Dictionary
> (through a caller-provided function), producing a new Dictionary.
>
> You could use this to take a dictionary [String:String] that maps user IDs
> to product IDs, and produce a dictionary [User:Product].
> Or you could invert a dictionary (swapping keys and values.)
Jens, this is untested outside of the repl, but maybe it will help:
extension Dictionary {
func dictMap<U, V>(closure: @noescape (k: Key, v: Value) -> (U, V)) ->
[U:V] {
var ret = [U:V]()
for (k0, v0) in self {
let (k1, v1) = closure(k: k0, v: v0)
ret[k1] = v1
}
return ret
}
}
let mapped = [1: 1, 2: 2].dictMap() { (k,v) in return (String(k),
String(v)) }
print(mapped)
// Prints:
// ["2": "2", "1": "1"]
Lou
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160829/ae0e2f9d/attachment.html>
More information about the swift-users
mailing list