# Dictionary subscript for value type default values

**URL:** <https://forums.swift.org/t/dictionary-subscript-for-value-type-default-values/83480>\
**Category:** Using Swift\
**Created:** [December 1, 2025, 9:18am UTC](https://forums.swift.org/t/dictionary-subscript-for-value-type-default-values/83480 "2025-12-01T09:18:32Z")\
**Posts on this page:** 1\
**Showing post:** 7

<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 2, 2025, 9:18am UTC](https://forums.swift.org/t/dictionary-subscript-for-value-type-default-values/83480/7 "2025-12-02T09:18:52Z")

</div>

Thank you for looking into it!

> [@tera](#):
>
> if worked

No, unfortunately (or fortunately?), it doesn't work. That was actually the thing that really confused me. I knew that adding classes (which present in official documentation). But it also didn't work but was never digging into details.

But turned, that adding value without modification never works for value types due to modify never called, i.e.:

```swift
let value = dict[1, default: "test"].count // or whatever non-mutating method is used

print(value) // prints `4`
print(dict) // prints `[:]`

```

I would say it is not intuitive and rather error prone. But now I think that maybe I should've put that in documentation section to add this note to the official docc here (same as for class): [subscript(\_:default:) | Apple Developer Documentation](https://developer.apple.com/documentation/swift/dictionary/subscript(_:default:))

> [@tera](#):
>
> There's a minute concern of calculating hash twice and doing lookup twice but unless your hash or EQ calculations are super-super heavy I'd not worry.

Yeah, I would also not be much concerned about integers or other basic primitives.  
And I see a solution from @lukasa to avoid hash re-calculation in other thread:

> [@Assigning a dictionary without re-hashing](https://forums.swift.org/t/assigning-a-dictionary-without-re-hashing/57699/9):
>
> I think the way you get this to work is to force the Dictionary into the \_modify accessor: extension Dictionary { mutating func setIfNotAlready(\_ value: @autoclosure () -\> Value, forKey key: Key) { self[key].setIfNil(value) } } extension Optional { fileprivate mutating func setIfNil(\_ newValue: () -\> Wrapped) { if self == nil { self = .some(newValue()) } } } You can see the code [for the \_modify accessor here](https://github.com/apple/swift/blob/a6ffb09fadb5ebe78762fbe8eaf82418c675a684/stdlib/public/core/NativeDictionary.swift#L411-L440), which includes only one call to…

So, if I ever have the problem in hashing at this path I know what to do, so can put it to some helpers.  
But I would vote to have this function in stdlib!

---

_[View the full topic](https://forums.swift.org/t/dictionary-subscript-for-value-type-default-values/83480)._
