How do I understand value semantics and copy-on-write in Swift?

Value semantics and copy-on-write are important concepts in Swift that help manage memory efficiently while maintaining performance. Understanding these concepts can aid developers in writing resilient and efficient code.

Value Semantics

In Swift, value types, such as structs and enums, have value semantics. This means that when you assign a value type to a variable or pass it to a function, a copy of the value is made. Each variable has its own instance, and changes to one instance do not affect others.

Copy-on-Write

Copy-on-write (COW) is an optimization technique that defers the copying of data until it is absolutely necessary. In Swift, this is typically associated with collections like arrays and dictionaries. If a copy is made and one of the copies is modified, only then will Swift create a new copy of the underlying data.

Example


struct Point {
    var x: Int
    var y: Int
}

var pointA = Point(x: 1, y: 2)
var pointB = pointA // pointB is a copy of pointA
pointB.x = 5 // Modifying pointB does not affect pointA
print(pointA.x) // Output: 1
print(pointB.x) // Output: 5

// Copy-on-Write example
var array1 = [1, 2, 3]
var array2 = array1 // Copy on write occurs here, no actual copying
array2.append(4) // Now array1 is copied since we're modifying array2
print(array1) // Output: [1, 2, 3]
print(array2) // Output: [1, 2, 3, 4]
    

Swift Value Semantics Copy-on-Write Structs Enums Memory Management