SwiftMidMCQ

What is copy-on-write (COW) and which types use it?

Test your knowledge:

Explanation & Code

Answer: Copy-on-write means a value type shares its underlying storage with copies until one of them is mutated — only then is a real copy made. This makes copying large collections cheap.

Code Example:

var array1 = [1, 2, 3, 4, 5]
var array2 = array1  // no copy yet — shared storage

array2.append(6)     // copy happens NOW — array1 is unaffected

print(array1) // [1, 2, 3, 4, 5]
print(array2) // [1, 2, 3, 4, 5, 6]

Types that use COW in Swift:

  • Array
  • Dictionary
  • Set
  • String
  • Data

Note: Custom structs do NOT get COW automatically. You have to implement it manually if needed.

Rate your understanding:

Ready to practice more Swift?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.