Conditional copy/clone on write

Representing nodes as value types has its downsides in Swift, and right now it would be probably much less efficient for general cases (with non-copyable generics it might get another chance - example of linked list)

I’m not sure what was your intention with inout here, but classes (reference types) in Swift can be mutated regardless of being declared as var or passed as inout. There is no equivalent to Rust’s let & let mut that would apply to all the types in the language. In Swift var has mutation consequences for value types (structs, enums and non-class protocols) only. So your Node type is currently freely modifiable by everyone as it is (declaring as let node = Node(...) still will allow modifications). You’d probably want to hide write access to its properties, if you want to implement Copy-on-Write behavior.

The closest thing that comes to mind is CFGetRetainCount which is available with Foundation framework on Apple platforms, and (at least according to code) is present in GitHub - apple/swift-corelibs-foundation: The Foundation Project, providing core utilities, internationalization, and OS independence to have it on Linux (Windows?) -- yet there are some confusion about foundation open source versions I'm not familiar close enough. I suppose Rc in Rust works roughly the same way, maybe with more native to language mechanisms, but do not know equivalent in Swift to CFGetRetainCount. So you can use this to replicate behaviour of conditional copy when count > 1.

4 Likes