[swift-evolution] Proposal: Add a sequence-based initializer to Dictionary
Brent Royal-Gordon
brent at architechies.com
Wed Jan 10 00:20:01 CST 2018
> On Jan 8, 2018, at 3:23 PM, Gregg Wonderly via swift-evolution <swift-evolution at swift.org> wrote:
>
> But why wouldn’t the key also be available so that you might be able to have selective handling of first vs last for each key?
Having only the values allows you to do some nice higher-order things, like:
let histogram = Dictionary(values.map { ($0, 1) }, uniquingValuesWith: +)
In other words, the same functions you could use with `reduce` can be used with `init(_:uniquingValuesWith:)`. If the function took a third parameter, we would lose this property.
There's a bunch of very reasonable things you can't do with `Dictionary(_:uniquingValuesWith:)`; for instance, you can't cause the initializer to fail by returning `nil`, only by throwing an error. Supporting these features would either complicate cases where you don't need them, or require us to provide another overload. Given that `Dictionary(_:uniquingValuesWith:)` and friends are just conveniences, and reimplementing them requires only a few lines of straightforward code, it's just not worth supporting every plausible variant.
(For what it's worth, the Swift Evolution proposal which added this initializer, [SE-0165 Dictionary & Set Enhancements](https://github.com/apple/swift-evolution/blob/master/proposals/0165-dict.md), touches on some of these issues. A big part of a proposal's role is to document the reasons for Swift's designs; if you ever wonder why something in Swift is designed the way it is, the feature's evolution proposal is a good place to start.)
--
Brent Royal-Gordon
Architechies
More information about the swift-evolution
mailing list