Browse Questions
  • Both static and class define type-level properties and methods, but static members cannot be overridden by subclasses (final), whereas class members allow dynamic dispatch and can be overridden.
  • A lazy property is only computed the first time it is accessed.
  • 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.
  • - Inheritance — a class derives behaviour from a parent class ("is-a" relationship) - Composition — a type gets behaviour by holding references to other objects ("has-a" relationship) Swift…

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.