How to implement copy-on-write behavior for my own collections?


#1

Swift Arrays, Sets, and Dictionaries are copy-on-write structs. The storage is shared between copies of the collection until one copy modifies the data, then it will receive a private copy that can be modified. I want to do something like that for a collection I’m implementing.

I looked at the Swift stdlib sources and this appears to be implemented using a function called isUniquelyReferenced(). This function appears to do lots of black-magic mojo.

Is there a ‘legit’ way to implement this? If it requires internals, is there a plan to make this an officially supported capability that can be safely used?


(Svein Halvor Halvorsen) #2

isKnownUniquelyReferenced(_:) does the trick and is as “legit” as anything. The documentation discusses how it can be used to implement copy-on-write:

https://developer.apple.com/documentation/swift/2429905-isknownuniquelyreferenced


#3

Excellent, thanks!