Skip to main content

Swift: Copy on Write Automatic vs Manual

Updated 3 min readMarkdown

For a long time I thought CoW happens automatically in Swift and I found that this is not entirely correct
Automatically CoW:
so for array, dictionary, set, string and data it happens automatically

// array holds value types
var a = [1, 2, 3]
var b = a
// array holds reference types
var x = [User(name: "Huda")]
var y = x

until now no copy happens, regardless of whether the array holds value or reference types
b.append(4)
now the copy happens and we will have 2 independent copies for a ([1, 2, 3]) and b ([1, 2, 3, 4])
y.append(User(name: "Tya"))
same now that the array is mutated we will have 2 copies of the array
- x has 1 element -> reference to Huda user
- y has 2 elements -> reference to the same Huda user and has reference to Tya user
so in both cases the copy happens when we mutated the array but in case the array holds reference types, the copy will increase the reference count
Manual CoW:
for structs and enums we need to implement copy on write manually

struct MyStruct { 
    var value: Int 
}

var a = MyStruct(value: 15)
var b = a

here even without mutating any property struct a copy will be copied in the assign step
but what if the struct has a property of reference type

class Storage { var value = 0 }
struct MyStruct { var storage = Storage() }
var a = MyStruct()
var b = a // the a struct variable will be copied in the assign step
b.storage.value = 5 // this will change the value in a and b as both pointing to the same storage object

the storage will not be copied, instead there will be another reference to it, this is expected but the problem is that struct should behave like value types (independent copies) but here it doesn't
This is where CoW makes sense: a and b can point to the same Storage object until one of them wants to mutate it, at this point each one will have its own object

class Storage { var value = 0 } 
struct MyStruct { 
 private var storage = Storage()
var value: Int {
    get {
        storage.value
    }
    set {
        if !isKnownUniquelyReferenced(&storage) {
            storage = Storage()// creates Storage with default value 0
        }
        storage.value = newValue
    }
}

} 
var a = MyStruct() 
var b = a 
b.value = 5

No comments yet. Be the first to comment.