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 <j...@mooseyard.com> wrote:
> 
> 
>> On Aug 31, 2016, at 10:51 AM, Daniel Tartaglia <danielt1...@gmail.com 
>> <mailto:danielt1...@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

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to