# Conditional copy/clone on write

**URL:** <https://forums.swift.org/t/conditional-copy-clone-on-write/72120>\
**Category:** Using Swift\
**Tags:** performance, reference, question, cow\
**Created:** [May 28, 2024, 5:10pm UTC](https://forums.swift.org/t/conditional-copy-clone-on-write/72120 "2024-05-28T17:10:43Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![vns](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vns/32/37396_2.png) [@vns](https://forums.swift.org/u/vns)\
**Post date:** [May 28, 2024, 7:20pm UTC](https://forums.swift.org/t/conditional-copy-clone-on-write/72120/2 "2024-05-28T19:20:11Z")

</div>

> [@carsonfarmer](#):
>
> Lastly, perhaps not using optional, and instead using a recursive enum to represent a Node or Empty

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](https://forums.swift.org/t/noncopyable-generics-in-swift-a-code-walkthrough/70862))

> [@carsonfarmer](#):
>
> `static func insert(node: inout Node<Key, Value>?, entry: Entry<Key, Value>) -> (Node<Key, Value>, Bool)`

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.

> [@carsonfarmer](#):
>
> Or more generally, how to match something like Rust's [RC::make\_mut](https://doc.rust-lang.org/std/rc/struct.Rc.html#method.make_mut) semantics in Swift?

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](https://github.com/apple/swift-corelibs-foundation) 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.

---

_[View the full topic](https://forums.swift.org/t/conditional-copy-clone-on-write/72120)._
