# Assigning a dictionary without re-hashing

**URL:** <https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699>\
**Category:** Using Swift\
**Created:** [May 30, 2022, 3:52pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699 "2022-05-30T15:52:29Z")\
**Posts on this page:** 18\
**Page:** 2

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [June 3, 2022, 2:15am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/21 "2022-06-03T02:15:18Z")

</div>

> [@lorentey](#):
>
> a part of which is spent calculating the hash value for the key

FWIW, I did a quick test: hash value calculation of `UUID().uuidString` based keys takes about 30ns on my old computer, if the whole access is 100ns it's quite significant chunk.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [June 24, 2022, 12:23am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/22 "2022-06-24T00:23:28Z")

</div>

> [@](#):
>
> let index = dict.index(forKey: key)!

> [@jrose](#):
>
> The dictionary index subscript returns a key-value pair as a tuple, and there’s no way to enforce that you only change the value and not the key. However, you _can_ mutate `dict.values[index]`

When is the dictionary element index invalidated or may become invalid? Haven't found it in the documentation 😲. Possible candidates:

1. when removing the indexed element (even if we are not using the index itself)
2. when removing an element (different from the indexed one)
3. when adding another element
4. when changing element values (including the indexed element). Excluding changing elements' values to `nil` which is equivalent to removing elements (see above).

Obviously in 1 and it also feels like in 2 & 3, but not 4, is this correct assumption?

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 24, 2022, 12:28am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/23 "2022-06-24T00:28:39Z")

</div>

That's a good question. In the absence of documentation, you must assume that _all_ indexes are invalidated on _any_ mutation. MutableCollection imposes some additional requirements, so you can assume that mutating through `dict.values[index]` does not invalidate indexes.

Strictly speaking, mutating through `dict[key]` _could_ invalidate indexes when `key` is already in the dictionary. It would be reasonable to ask for that as a guarantee in the documentation.

#1 and #3 can absolutely invalidate. #2 may or may not, but it's an implementation decision that I suspect we don't want to promise anything about.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [June 24, 2022, 12:59am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/24 "2022-06-24T00:59:36Z")

</div>

Thank you.

Do you know if the following `foo` and `bar` are equivalent?

```swift
struct Item {
    var foo: Int = 0
    var bar: String = ""
}

var items: [String: Item] = ...

func change(_ item: inout Item) {
    item.foo += 1
}

func foo(key: String) {
    change(&items[key, default: Item()])
}

func bar(key: String) {
    var item = items[key, default: Item()]
    change(&item)
    items[key] = item
}

```

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [June 24, 2022, 1:07am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/25 "2022-06-24T01:07:51Z")

</div>

They should have the same effect; for a subscript implemented with `get` and `set` they would have the same behavior as well. However, a subscript implemented with `_modify` could provide an optimized implementation that only has to do one lookup of `key`.

---

<div class="post-metadata">

**Author:** ![lorentey](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lorentey/32/1299_2.png) [@lorentey](https://forums.swift.org/u/lorentey)\
**Post date:** [June 24, 2022, 8:50pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/26 "2022-06-24T20:50:10Z")

</div>

`Dictionary` never invalidates indices when changing the value of an existing key. This is not explicitly spelled out in the docs, but an important hint is that the `Dictionary.Values` view is a `MutableCollection`.

(We go to extraordinary lengths to preserve indices on value mutations even when the original dictionary is a "verbatim bridged" `NSDictionary` instance. There is some eldritch code hiding in there -- consider that `NSDictionary` doesn't really model indices at all. 😅)

`Dictionary` does provide the following guarantee about index invalidation vs insertions:

> A dictionary’s indices stay valid across additions to the dictionary as long as the dictionary has enough capacity to store the added values without allocating more buffer. When a dictionary outgrows its buffer, existing indices may be invalidated without any notification.
> 
> When you know how many new values you’re adding to a dictionary, use the `init(minimumCapacity:)` initializer to allocate the correct amount of buffer.

I believe this originated in C++. I find this is a rather unfortunate guarantee, as it prevents the Dictionary from reordering collision chains on insertion to improve average lookup performance (as in round robin hashing). For better or worse, we are stuck with it now, though.

Removing a key from a `Dictionary` always invalidates every index within it, as the removal operation involves rearranging the collision chain that included the original item.

`Set` operates the same way.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [June 24, 2022, 9:47pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/27 "2022-06-24T21:47:13Z")

</div>

> [@lorentey](#):
>
> `Dictionary` never invalidates indices when changing the value of an existing key. This is not explicitly spelled out in the docs, but an important hint is that the `Dictionary.Values` view is a `MutableCollection`.

Can we formalize this guarantee?

---

<div class="post-metadata">

**Author:** ![lorentey](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lorentey/32/1299_2.png) [@lorentey](https://forums.swift.org/u/lorentey)\
**Post date:** [June 27, 2022, 6:16pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/28 "2022-06-27T18:16:48Z")

</div>

> [@xwu](#):
>
> Can we formalize this guarantee?

Absolutely. This is a (semantic) API change, so I expect it'll require going through Swift Evolution. I've been collecting other ill-defined aspects of the stdlib -- perhaps we have a large enough batch of these now to be worth the expense of a small proposal.

> [@Regression in Set with Swift 5.5](https://forums.swift.org/t/regression-in-set-with-swift-5-5/53130/19):
>
> That would be an excellent idea! Are you volunteering to write it up? So right now we have: Sequence.sorted(), .sorted(by:), MutableCollection.sort(), .sort(by:) should document that the sort algorithm is stable. (Starting from Swift x.y) Set.union(\_:), Set.intersection(\_:), and Set.formIntersection(\_:) (all overloads) should document that members of the result that appear in both inputs are taken from self. (Interestingly, formUnion already has this guarantee.) (Starting from Swift 5.6) A…

(Edit: [unifying and documenting the expected behavior of `base` properties on mutable slices](https://forums.swift.org/t/how-to-find-range-in-new-string-after-replacingcharacters-in-range-with-c/58367/17) could also be part of this, although that one also requires actual behavioral changes in some obscure corners of the stdlib.)

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [June 27, 2022, 6:31pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/29 "2022-06-27T18:31:37Z")

</div>

> [@lorentey](#):
>
> (Edit: [unifying and documenting the expected behavior of `base` properties on mutable slices](https://forums.swift.org/t/how-to-find-range-in-new-string-after-replacingcharacters-in-range-with-c/58367/17) could also be part of this, although that one also requires actual behavioral changes in some obscure corners of the stdlib.)

IMO, dealing with `base` semantics is big enough to tackle on its own, particularly if the rest of the semantic changes are going to be uncontroversial and require little debate.

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [September 2, 2022, 2:59am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/30 "2022-09-02T02:59:54Z")

</div>

> [@lorentey](#):
>
> Another way of doing this is to use the `Dictionary` subscript operation that allows specifying a default value. Unfortunately this still requires a helper function to force things through the `_modify` accessor, but it's slightly simpler:
> 
> ```swift
> func modify<T>(_ value: inout T) { }
> 
> extension Dictionary {
> mutating func setIfNotAlready(_ value: @autoclosure () -> Value, forKey key: Key) {
> modify(&self[key, default: value()])
> }
> }
> 
> ```
> 
> Ideally the standard library would supply a version of this out of the box. I have been toying with something like this variant:

i just do

```swift
{ _ in }(&dictionary[key, default: value])

```

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [September 2, 2022, 4:03am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/31 "2022-09-02T04:03:21Z")

</div>

> [@taylorswift](#):
>
> i just do
> 
> ```swift
> { _ in }(&dictionary[key, default: value])
> 
> ```

Looks quite cryptic. 🙂

_I still wonder though whether the whole issue could be sidestepped (and as a bonus the overall app/system performance gain achieved) if we somehow cache the calculated hash value to tremendously reduce the number of hash calculations (and also provide a quick path to test if the two values aren't equal) – I guess this is only realistically possible with reference types or with value types like string/uuid/array/dictionary/etc (and their specific variants) that are backed by reference types. If to approach this systematically the first thing I'd do is somehow measure the time spent for hashing calculations (plus the EQ calculations that end up being false) in some realistic benchmarks, then if it's, say, 10% it's worth exploring further, if 1% - doesn't worth the complexity._

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [September 2, 2022, 5:02pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/32 "2022-09-02T17:02:38Z")

</div>

i like `{ _ in }(&)`. it’s short, clear about what it’s doing, easy for the compiler to detect and optimize, and doesn’t make us design and pitch and review and lobby a new feature. i just wish it didn’t need a semicolon on the previous statement.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [September 2, 2022, 10:08pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/33 "2022-09-02T22:08:12Z")

</div>

> [@taylorswift](#):
>
> clear about what it’s doing

Mmm…

---

<div class="post-metadata">

**Author:** ![michelf](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michelf/32/1180_2.png) [@michelf](https://forums.swift.org/u/michelf)\
**Post date:** [September 2, 2022, 11:32pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/34 "2022-09-02T23:32:34Z")

</div>

Personally, I'd love to be able to express this:

```swift
dict[key] = dict[key] ?? value

```

as this:

```swift
dict[key] ??= value

```

Let's call it the `nil`-replacement operator. It'd work anywhere you have an optional, not only with dictionaries. And the intent is clear, unlike `modify(&)` or `{ _ in }(&)`.

> **Basic Implementation**
>
> ```swift
> infix operator ??=
> 
> func ??= <T>(a: inout T?, b: @autoclosure () -> T?){
> if a == nil {
> a = b()
> }
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![eskimo](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/eskimo/32/13558_2.png) [@eskimo](https://forums.swift.org/u/eskimo)\
**Post date:** [September 3, 2022, 10:16am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/35 "2022-09-03T10:16:56Z")

</div>

> clear about what it’s doing

Just as a data point, I had to copy that code into a test project and dissect it into parts to figure out what it was doing )-:

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [September 3, 2022, 6:31pm UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/36 "2022-09-03T18:31:06Z")

</div>

well i suppose it takes getting used to, like `@available(*, unavailable)` or `some` vs `any`. all the alternatives suggested here so far involve adding new API to the standard library (or even new operators!) which feels like overkill to me.

---

<div class="post-metadata">

**Author:** ![lukasa](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lukasa/32/1232_2.png) [@lukasa](https://forums.swift.org/u/lukasa)\
**Post date:** [September 5, 2022, 8:46am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/37 "2022-09-05T08:46:36Z")

</div>

I can see no world in which I would add this code to a project when I can use the `func modify` solution proposed by @lorentey upthread. I appreciate that these features compose this way and I'm glad this all works, but it's sufficiently inscrutable that I would encourage any team I work in to avoid this in favour of a named method whose intention is far clearer.

---

<div class="post-metadata">

**Author:** ![blindspotbounty](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/blindspotbounty/32/44760_2.png) [@blindspotbounty](https://forums.swift.org/u/blindspotbounty)\
**Post date:** [December 1, 2025, 11:05am UTC](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/38 "2025-12-01T11:05:07Z")

</div>

> [@lukasa](#):
>
> I think the way you get this to work is to force the `Dictionary` into the `_modify` accessor

Nice approach.  
I wonder if there is some plan to add this to stdlib?

[Previous page](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699.md?page=1)
