[swift-evolution] [Proposal Draft] Provide Custom Collections for Dictionary Keys and Values

Daniel Vollmer lists at maven.de
Wed Oct 12 05:40:13 CDT 2016


I very much think the points mentioned in the motivation are worth addressing (and IMO this is not an area where “maybe the optimizer can be made smarter” can cut it; I want performance guarantees, not hopes).

> On 11 Oct 2016, at 23:28, Nate Cook via swift-evolution <swift-evolution at swift.org> wrote:


On a shallow read I like presented approach, except for

> Both the keys and values collections share the same index type as Dictionary. This allows the above sample to be rewritten as:
> // Using `dict.keys.index(of:)`
> if let i = dict.keys.index(of: "one") {
>     dict.values[i].append(1)
> } else {
>     dict["one"] = [1]
> }

The asymmetry between the if / else branches seems ugly to me. That is once obtaining the value “directly” from dict, and once through the values-view. I don’t have a great solution here, but is is possible to subscript the dict by its `Index` as well as its `Key`?

// Using `dict.keys.index(of:)`
if let i = dict.keys.index(of: "one") {
} else {
    dict["one"] = [1]

On another note, I’m not sure whether there is a way (or whether it’s even worth trying) to avoid hashing the key twice when the `else` branch is taken.


More information about the swift-evolution mailing list