Skip to main content
InterviewHubPRO
Section Overview
Q11

Question 11 of 50

Part 2: Concurrency, Actors & Advanced Architecture (11 - 24)

22%
Swift & Concurrency (50 Qs)•Part 2: Concurrency, Actors & Advanced Architecture (11 - 24)

What is Copy-On-Write (COW) in Swift and how do you implement it for custom structs?

senior LevelCode ExampleSystem Design

In Simple Words: Standard Swift collections (Array, Dictionary, String) are value types with Copy-On-Write optimization:

  • When you assign b = a, memory is not duplicated immediately; both variables share the same underlying memory buffer.
  • Memory is only duplicated when one of the variables attempts to mutate data!
  • Custom Implementation: Wrap a reference type (class) inside a struct and check isKnownUniquelyReferenced(&ref) before mutation:
swift
struct CustomBuffer {
    private var storage = StorageClass()

    mutating func write(data: String) {
        if !isKnownUniquelyReferenced(&storage) {
            storage = storage.copy() // Duplicate buffer only upon mutation!
        }
        storage.data = data
    }
}