Why is this variable first set to null then the new value

In the code from this link:

backing = .null // HERE
object[key] = ref
backing = .object(object)

I don’t understand why backing is set to null first before getting the new value, instead of just assigning the new value after configuring it.

My best guess is that this avoids Copy-On-Write by keeping the number of references to the underlying collection type to only one. However, I couldn’t find any material that explicitly confirms my guess.

Also, if that's true, it makes me paranoid about my responsibilities for writing code. I always thought my job is to write functional code and this kind of optimization should be all left to compiler. But it doesn't seem to be the case here.


It is not currently possible to directly mutate an enum’s payload. While it is possible the compiler might do it as an optimisation, for some code it’s important to ensure it happens. What you’d need for that is to be able to create an inout binding to the payload.

The recent noncopyable switch proposal lays important groundwork in that direction and mentions it as future work:

inout pattern matches

With this proposal, pattern matches are able to borrow and consume their subjects, but they still aren't able to take exclusive inout access to a value and bind parts of it for in-place mutation. This proposal lays the groundwork for supporting this in the future; we could introduce inout bindings in patterns, and introducing mutating switch behavior as a level of ownership strictness between borrowing and consuming.


i agree with your guess, that pattern was a ritual from the Swift 5.4 days and you still see it in a lot of code bases today. in theory the consume/consuming keywords are supposed to replace this, but there are some bugs to be ironed out with those, so the ritual lives on.

these threads also discusses a similar topic: Appending to an Array stored in an enum case payload: O(1) or O(n)? - #3 by lukasa

1 Like