Swift Copy-on-Write PSA: Mutating Dictionary Entries
Swift’s copy-on-write system usually helps efficiency by delaying the copying of structs until it’s actually needed. However, as shown here, you can run into some pitfalls if you aren’t vigilant of what’s going on under the hood.
[…]
The “gotcha” here is that at the time of
append
, the array is referenced twice – once by the dictionary, and once by the variableitems
. This triggers copy-on-write, meaning that the entire array is copied to a new location in memory, even though your intention is to mutate a single array.
This is a doubly weird example in Swift because you can’t actually mutate dictionary entries where the value is a struct such as an array. You have to set the array again after appending or wrap the array in a reference type.
Update (2016-11-15): See also: Optimizing a copy-on-write double-ended queue in Swift.