[swift-users] Mapping a Dictionary to a Dictionary?
Daniel Tartaglia
danielt1263 at gmail.com
Wed Aug 31 15:13:54 CDT 2016
Sorry, I was too quick to send that email… Here is something from a playground that works:
extension Dictionary {
/// An immutable version of update. Returns a new dictionary containing self's values and the key/value passed in.
func withUpdate(key: Key, value: Value) -> Dictionary<Key, Value> {
var result = self
result[key] = value
return result
}
}
let dict1 = ["joe": 3, "mary": 4]
let dict2 = dict1.reduce([:]) { dict2, element in dict2.withUpdate(element.0, value: element.1 * 5) }
print(dict2)
Remember, map can be implemented in terms of reduce…
> On Aug 31, 2016, at 2:17 PM, Jens Alfke <jens at mooseyard.com> wrote:
>
>
>> On Aug 31, 2016, at 10:51 AM, Daniel Tartaglia <danielt1263 at gmail.com <mailto:danielt1263 at gmail.com>> wrote:
>>
>> I use the below to do this:
>>
>> dict2 = dict1.map { $0.withUpdate($0.0, value: $0.1) }
>
> I don’t see how this can work. Dictionary.map returns an Array, not a Dictionary.
> Also, in the callback function $0 is the key, so your Dictionary.withUpdate method only makes sense if the key type of the Dictionary is another Dictionary, which seems … very unusual.
>
> (To clarify, I wasn’t asking how to accomplish this; it’s pretty simple to write it either as an extension method or as a simple one-off ‘for’ loop. I was just making sure it wasn’t already in the standard library, since it seems an obvious thing to have.)
>
> —Jens
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160831/305fc030/attachment.html>
More information about the swift-users
mailing list