[swift-users] Mapping a Dictionary to a Dictionary?

Zhao Xin owenzx at gmail.com
Mon Aug 29 18:38:43 CDT 2016


Jens, I see now. I believe this is talked months ago. There is no directly
function at the moment.  You can do:

var dict1:[String:String] = ...
var dict2: [User:Product] = [:]
_ = dict1.map {
    ....
    dict2.updateValue(value, forKey:key)

    return nil
}

// use dict2

It is ugly, but it works. However, some people thought this was not a good
use of map. And they make an extension of Dictionary themselves.

You can search it in [swift-user], [swift-evolution] if you can't find it
in [swift-user].

Zhaoxin

On Tue, Aug 30, 2016 at 5:52 AM, Jens Alfke <jens at mooseyard.com> wrote:

>
> > On Aug 29, 2016, at 2:07 PM, Zhao Xin <owenzx at gmail.com> wrote:
> >
> > I don''t quite understand your question. In Swift, Dictionaries are
> structs. You can always use `let dict2 = dict1`.
>
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160830/2a20d20a/attachment.html>


More information about the swift-users mailing list