Monday, February 20, 2017

Provide Custom Collections for Dictionary Keys and Values


This proposal address two problems:

  • While a dictionary’s keys collection is fine for iteration, its implementation is inefficient when looking up a specific key, because LazyMapCollection doesn’t know how to forward lookups to the underlying dictionary storage.
  • Dictionaries do not offer value-mutating APIs. The mutating key-based subscript wraps values in an Optional. This prevents types with copy-on-write optimizations from recognizing they are singly referenced.


Dictionary values can be modified through the keyed subscript by direct reassignment or by using optional chaining. Both of these statements append 1 to the array stored by the key "one":

// Direct re-assignment
dict["one"] = (dict["one"] ?? []) + [1]

// Optional chaining

Both approaches present problems.

The proposed solution is an improvement but still seems a bit awkward.

Update (2017-02-20): Airspeed Velocity:

There are other changes likely for Swift 4 that would make this less awkward (e.g. to supply a default value when subscripting).

It’s just that this particular change was ABI impacting (changes the type of Dictionary.Value) so was proposed during stage 1.

1 Comment RSS · Twitter

[…] Previously: Swift.Codable, Swift 4: Key-Value Observation, Swift’s Error Handling Implementation, Swift 4: Bridging Peephole for “as” Casts, Swift 4: Synthesizing Equatable and Hashable Conformance, Swift 4: JSON With Encoder and Encodable, Swift 4 String Manifesto, Provide Custom Collections for Dictionary Keys and Values. […]

Leave a Comment