8

I read about copy-on-write implementation for Array in Swift here.

Arrays, like all variable-size collections in the standard library, use copy-on-write optimization. Multiple copies of an array share the same storage until you modify one of the copies. When that happens, the array being modified replaces its storage with a uniquely owned copy of itself, which is then modified in place. Optimizations are sometimes applied that can reduce the amount of copying.

I was wondering if you have any information about which structure supports copy-on-write.

SwiftyFinch
  • 445
  • 2
  • 12

1 Answers1

10

Copy-on write is supported for String and all collection types - Array, Dictionary and Set.

Besides that, compiler is free to optimize any struct access and effectively give you copy-on-write semantics, but it is not guaranteed.

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159
  • 2
    "not guaranteed" is one way to put it. If you want copy-on-write semantics, you use `isKnownUniquelyReferenced(&ref)` explicitly. (also you "must only call this function from mutating methods with appropriate thread synchronization"; note that text does not point to how the standard unsynchronized collections manage to avoid violating this. [Nor does this official doc](https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst#advice-use-copy-on-write-semantics-for-large-values)) https://marcosantadev.com/copy-write-swift-value-types/ – sourcejedi Sep 27 '17 at 19:34
  • I don´t think its a compiler feature. Nowhere says that. – PabloR Mar 11 '18 at 15:07