>
> 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
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to