[SR-13879] Dictionary.Indices retains dictionary, causes CoW on mutation during loop #56277
Labels
bug
A deviation from expected or documented behavior. Also: expected but undesirable behavior.
standard library
Area: Standard library umbrella
Environment
Apple Swift version 5.3.1 (swiftlang-1200.0.41 clang-1200.0.32.8)
Target: x86_64-apple-darwin19.6.0
Additional Detail from JIRA
md5: 777a286e1be306db5fbbabc110c4b471
relates to:
Issue Description:
If I'm iterating over a dictionary's indices and mutating the dictionary in the loop, it does a copy-on-write on the first mutation. This is a surprising and hard to discover. I verified this by printing out the variant's native instance address in LLDB to confirm reallocation.
Comparing the
dict._variant.object.nativeInstance
before and after the loop shows different addresses.This is a consequence of the fact that
Dictionary
usesDefaultIndices
, andDefaultIndices
keeps a reference to the collection.More generally,
DefaultIndices
does not seem to be safe to use with any mutable collection as there is no way for it to walk the collection's indices without keeping a strong reference to the collection.The text was updated successfully, but these errors were encountered: