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.
Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!
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.
Hacking with watchOS
Transfer your Swift skills to watchOS the easy way, and learn to build real-world apps in the process!