[swift-users] How to merge two dictionaries?

Martin R martinr448 at gmail.com
Fri Nov 11 02:50:02 CST 2016


Nate Cook proposed merging dictionary initializers (with optional conflict resolution) to be added to the standard library:

  SE-0100 Add sequence-based initializers and merge methods to Dictionary
  https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md

Martin


> On 11 Nov 2016, at 09:14, Ray Fix via swift-users <swift-users at swift.org> wrote:
> 
> Hi Mr Bee,
> 
> The reason I don’t think it is provided is because it is difficult to know what to do when keys collide.  You could easily write such a thing and decide your own policy.  For example:
> 
> let d1 = ["Apples": 20, "Oranges": 13]
> let d2 = ["Oranges": 3, "Cherries": 9]
> 
> extension Dictionary {
>     func merged(with another: [Key: Value]) -> [Key: Value] {
>         var result = self
>         for entry in another {
>             result[entry.key] = entry.value
>         }
>         return result
>     }
> }
> 
> let result = d1.merged(with: d2)
> 
> 
>> On Nov 11, 2016, at 12:05 AM, Mr Bee via swift-users <swift-users at swift.org> wrote:
>> 
>> Hi,
>> 
>> I'm using Swift v3 on an El Capitan machine. I want to merge a dictionary into another compatible dictionary. However, I couldn't find addEntries function in the dictionary instance, like it was on NSMutableDictionary (https://developer.apple.com/reference/foundation/nsmutabledictionary). 
>> 
>> Does that mean that Swift standard library won't provide such similar function for native Swift dictionary? Or is there any other way of doing that natively? I mean using the built-in Swift's native dictionary function (https://developer.apple.com/reference/swift/dictionary), no need to write a custom function, or bridging to NSMutableDictionary.
>> 
>> Thank you.
>> 
>> Regards,
>> 
>> –Mr Bee
>> 
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list