[swift-evolution] Proposal: Add a sequence-based initializer to Dictionary

Gwendal Roué gwendal.roue at gmail.com
Fri Jan 15 03:04:48 CST 2016


Agreed, for three reasons:

1. A failable initializer would require the user to validate the input sequence, which is painful, and inefficient. Do you see yourself checking if `Set(sequence.map { $0.0 }).count == 1` before creating the dictionary ? If user cares about unique keys, it’s much easier to post-check for `dic.count == input.count`.

2. We can assume that users will be well aware that a dictionary builder from a sequence will lose information for duplicated keys, just as users are already well aware that an inversed dictionary (key <-> values) loses information for duplicated values. A failable initializer would actually *surprise* most users.

3. A clear rule on which value is used in case of duplicated key (such as: the last one is used) allows users to opt-in for explicit choice of the first one by reversing the sequence.

Gwendal

> Le 15 janv. 2016 à 09:45, David Hart via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> It may sound counter-intuitive to have such an initialiser failable for many users. I *think* I would prefer it to silently use the last key.
> 
>> On 15 Jan 2016, at 01:31, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>>> One caveat is that the new initializer doesn't prevent using a sequence with multiple identical keys. In such a case, the last key/value would "win" and exist in the dictionary.
>> 
>> Another alternative would be to make the initializer failable and have it fail if a key is duplicated.
>> 
>> -- 
>> Brent Royal-Gordon
>> Architechies
>> 
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list