Swift version: 5.0
Copy on write is a common computing technique that helps boost performance when copying structures. To give you an example, imagine an array with 1000 things inside it: if you copied that array into another variable, Swift would have to copy all 1000 elements even if the two arrays ended up being the same.
This problem is solved using copy on write: when you point two variables at the same array they both point to the same underlying data. Swift promises that structs like arrays and dictionaries are copied as values, like numbers, so having two variables point to the same data might seem to contradict that. The solution is simple but clever: if you modify the second variable, Swift takes a full copy at that point so that only the second variable is modified - the first isn't changed.
So, by delaying the copy operation until it's actually needed, Swift can ensure that no wasted work is done.
Warning: copy on write is a feature specifically added to Swift arrays and dictionaries; you don't get it for free in your own data types.
SPONSOR Tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize your debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically. It only takes a line of code to setup. Get started for free.
Available from iOS 7.0
Did this solution work for you? Please pass it on!
Other people are reading…
About the Swift Knowledge Base
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.