Understanding Swift Copy-on-Write mechanisms

What is this Copy-on-Write?

Something really important to know is …

Copy-on-Write is not a default behavior of value types, is something that is implemented on the Swift Standard Library for certain types such as Array and Collections. So, it means that not every value type in the Standard Library has this behavior. Also, the value types that you create doesn’t have it, unless you implement it yourself. This is something I’ll talk about later in the next section.

Implementing Copy-on-Write behavior for your custom value types

You can implement Copy-on-Write behavior yourself to take advantage of this with your custom value types. The example below can be found on OptimizationTips.rst in the Swift main repo.

Conclusion

Copy-on-Write is a very intelligent way to optimize copy of value types and that is a mechanism heavily used in Swift, even though most of the times we don’t see it explicitly because fortunately, it’s implementation is done for us on the Standard Library. But is definitely something good to know so we can do our daily code implementations in a way that take full advantage of this.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luciano Almeida

Luciano Almeida

iOS Developer, Swift and OpenSource enthusiast