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 checkisKnownUniquelyReferenced(&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
}
}