Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Value Semantics and Copy-On-Write

Swift Value Semantics and Copy-On-Write

Value semantics means that after a value is copied, the two copies do not affect each other.

Swift's structs, enums, and standard library containers have value semantics by default, but once a struct holds a reference type internally, shared state can creep in unnoticed.

This article begins with the official definition, then breaks down the principle of copy-on-write and the pitfalls it brings.


Value Semantics and Reference Semantics

The definition given in The Swift Programming Language is: when a value type is assigned to a variable or constant, or passed as an argument to a function, its value is copied.

Reference types are the opposite: assignment or argument passing does not copy; instead, the same instance is shared.

In other words, to determine which category a type belongs to, you only need to examine three operations: initialization, assignment, and argument passing.

Operation Value types (struct / enum) Reference types (class)
Initialization Create an independent value Create an instance; the variable holds a reference to it
Assignment Copy the value; the two copies do not affect each other Copy the reference; both variables point to the same instance
Argument passing Pass a copy; modifications inside the function do not affect the caller Pass a reference; modifications inside the function are visible to the caller

Let's compare these two behaviors using the same coordinate model.

Example

import Foundation

// Value type: coordinate

struct

PointValue

{

    var x

:

Int

    var y

:

Int

}

// Reference type: coordinate

final

class

PointReference

{

    var x

:

Int

    var y

:

Int

    init

(

x

:

Int, y

:

Int

)

{

        self.

x

=

x

        self.

y

=

y

   

}

}

var p1

=

PointValue

(

x

:

1

, y

:

2

)

var p2

=

p1          

// Assignment: copy out an independent value

p2.

x

=

100

         

// Modify p2; p1 is completely unaffected

var q1

=

PointReference

(

x

:

1

, y

:

2

)

var q2

=

q1          

// Assignment: both variables point to the same instance

q2.

x

=

100

         

// Modify q2; q1 sees the same data

print

(

"Value type p1: (p1.x), (p1.y)"

)

print

(

"Value type p2: (p2.x), (p2.y)"

)

print

(

"Reference type q1: (q1.x), (q1.y)"

)

print

(

"Reference type q2: (q2.x), (q2.y)"

)

Running the above code produces the following output:



值类型 p1:1, 2

值类型 p2:100, 2

引用类型 q1:100, 2

引用类型 q2:100, 2

Argument passing follows the same set of rules.

Example

// Pass by value: the parameter is itself a copy

func moveValue

(

_ point

:

PointValue

)

PointValue

{

    var copy

=

point

    copy.

x

=

1

   

return

copy

}

// Pass by reference: the parameter and the argument are the same instance

func moveReference

(

_ point

:

PointReference

)

{

    point.

x

=

1

}

var value

=

PointValue

(

x

:

0

, y

:

0

)

let moved

=

moveValue

(

value

)

print

(

"After passing, value.x = (value.x), returned moved.x = (moved.x)"

)

var reference

=

PointReference

(

x

:

0

, y

:

0

)

moveReference

(

reference

)

print

(

"After passing, reference.x = (reference.x)"

)

Running the above code produces the following output:



传参后 value.x = 0,返回值 moved.x = 1

传参后 reference.x = 1


The Two Are Indistinguishable Without Mutability

An often-overlooked fact is that when a type is completely immutable, value types and reference types are behaviorally indistinguishable.

Because no operation can change the value itself, an observer can never see the difference between "two copies" and "the same instance."

The difference between value and reference semantics becomes apparent only at the moment a modification occurs.

Example

// A struct whose properties are all let

struct

ImmutablePointValue

{

    let x

:

Int

    let y

:

Int

}

// A class whose properties are all let

final

class

ImmutablePoint

{

    let x

:

Int

    let y

:

Int

    init

(

x

:

Int, y

:

Int

)

{

        self.

x

=

x

        self.

y

=

y

   

}

}

var a

=

ImmutablePointValue

(

x

:

1

, y

:

2

)

var b

=

a                    

// Copy

var c

=

ImmutablePoint

(

x

:

1

, y

:

2

)

var d

=

c                    

// Share

// There is no way to modify the data inside a, b, c, d,

// so "copy" and "share" have exactly the same observable behavior here

print

(

"a = ((a.x), (a.y))"

)

print

(

"b = ((b.x), (b.y))"

)

print

(

"c = ((c.x), (c.y))"

)

print

(

"d = ((d.x), (d.y))"

)

print

(

"c and d are the same instance: (c === d)"

)

Running the above code produces the following output:



a = (1, 2)

b = (1, 2)

c = (1, 2)

d = (1, 2)

c 与 d 是同一个实例:true

Value types have no notion of identity and cannot be compared with ===, which also makes them simpler when immutable.

Note:The "indistinguishability" mentioned here applies only to observable behavior. Reference types can still use === to judge identity; it's just that in a fully immutable scenario this identity difference does not affect any business outcome.


struct Does Not Equal Value Semantics

Writing a struct only makes the type copy by value at the syntax level; it does not automatically bring full value semantics.

Because what gets copied is the struct's stored content: if it holds a reference, only that reference is copied, and the underlying object is still shared.

Conversely, a completely immutable class can also behave like a value in use.

To determine whether a struct truly has value semantics, you must check whether each of its stored properties also has value semantics.

Example

// This struct appears to be a value type,

// but its score property is a reference type, so shared state still exists

final

class

Score

{

    var point

:

Int

    init

(

point

:

Int

)

{

        self.

point

=

point

   

}

}

struct

Student

{

    var name

:

String

    var score

:

Score

}

let sharedScore

=

Score

(

point

:

60

)

var studentA

=

Student

(

name

:

"Xiao Ming"

, score

:

sharedScore

)

var studentB

=

studentA    

// The struct is copied, but score only copies the reference

print

(

"The two scores are the same instance: (studentA.score === studentB.score)"

)

Running the above code produces the following output:



两个 score 是同一个实例:true

The standard library's Array is also a struct, yet it genuinely has value semantics.

The secret is that its internal buffer implements copy-on-write; the next modification copies the shared buffer into a private one.


The Principle of Copy-on-Write (COW)

Copy-on-write (COW) is a lazy copying strategy: share first, and copy only when a write actually happens.

Value semantics vs. reference semantics: after var b = a, for value types b is an independent copy and changing b does not affect a; for reference types a and b point to the same object, so changing b affects a. The bottom shows the copy-on-write process of Array: assignment only copies the buffer reference, and a private buffer is actually copied only on the first write when the reference count is greater than 1.

Taking Array as an example, it holds a buffer on the heap internally, and that buffer carries a reference count.

When the array is assigned to another variable, only the buffer's reference is copied and the count is incremented; not a single element is copied.

Only when one copy is about to be written and the buffer's reference count is greater than 1 is a private buffer actually copied out.

If the reference count equals 1, no one else is using it, so the write happens in place with no extra overhead.

Conditional Description
The underlying buffer is shared in multiple places The buffer's reference count is greater than 1
A write operation occurs append, subscript assignment, mutating methods, and so on

A real copy happens only when both conditions are met; read-only traversal and assignment without modification produce no copies.

Example

// Assignment does not copy elements; both arrays share the same underlying buffer

var list1

=

[

1

,

2

,

3

]

var list2

=

list1

// Copying happens only on write: list2 gets its own buffer

list2.

append

(

4

)

print

(

"list1 = (list1)"

)

print

(

"list2 = (list2)"

)

Running the above code produces the following output:



list1 = [1, 2, 3]

list2 = [1, 2, 3, 4]

Note:COW is an optimization, not a semantic guarantee. It guarantees behavioral independence; whether buffers are shared internally is an implementation detail.


Implementing Copy-on-Write Yourself

The standard library uses isKnownUniquelyReferenced(&) to check whether a buffer is unique; we can use it to add COW to our own types.

The idea is to use a reference type as the buffer; the struct checks whether the buffer is shared before writing and copies it first if so.

Example

import Foundation

// Reference-type buffer

final

class

Box

<

T

{

    var value

:

T

    init

(

_ value

:

T

)

{

        self.

value

=

value

   

}

}

// A struct with copy-on-write capability

struct

RunoobBox

<

T

{

private

var box

:

Box

<

T

init

(

_ value

:

T

)

{

        box

=

Box

(

value

)

   

}

    var value

:

T

{

        get

{

return

box.

value

}

        set

{

           

// If the buffer is shared by others, copy it first; otherwise modify in place

           

if

!

isKnownUniquelyReferenced

(

&

box

)

{

                box

=

Box

(

newValue

)

           

}

else

{

                box.

value

=

newValue

           

}

       

}

   

}

}

var x

=

RunoobBox

(

"www.runoob.com"

)

var y

=

x                      

// At this point x and y share the same Box

y.

value

=

"RUNOOB"

             

// When y writes, it finds the buffer is not unique and copies it first

print

(

"x = (x.value)"

)

print

(

"y = (y.value)"

)

Running the above code produces the following output:



x = www.runoob.com

y = RUNOOB

Note that the argument to isKnownUniquelyReferenced must be a mutable reference to a class instance, so it is passed as &box, and that reference itself must be writable.


The Pitfall of Nesting Reference Types in Value Types

When value and reference types are mixed, the most common problem is "change one and the other changes too."

In the example below, Student is a struct, but its score property is a reference type.

When the struct is copied, name is independent, but score points to the same object.

Example

let sharedScore

=

Score

(

point

:

60

)

var studentA

=

Student

(

name

:

"Xiao Ming"

, score

:

sharedScore

)

var studentB

=

studentA            

// The struct is copied

studentB.

name

=

"Xiao Hong"

             

// Change the name: A is unaffected

studentB.

score

.

point

=

100

         

// Change the score: it is still the same Score instance underneath

print

(

"A: (studentA.name)'s score is (studentA.score.point)"

)

print

(

"B: (studentB.name)'s score is (studentB.score.point)"

)

Running the above code produces the following output:



A:小明 的分数是 100

B:小红 的分数是 100

The name is independent while the score is shared, which is exactly the practical consequence of "struct does not equal value semantics."

There are three common ways to avoid this pitfall.

Approach Description
Make the internal reference type immutable Use let for all properties letso sharing is irrelevant either way
Implement COW in the internal type as well Detect sharing on write and copy, like standard library containers
Manually deep-copy when copying Copy the internal object along with the struct; this is relatively costly

inout and Exclusive Access

Value types are passed by value by default, but this does not mean every argument pass necessarily makes a copy.

An inout parameter lends the caller's variable to the function; modifications inside the function act directly on the original storage and create no copy.

Example

// inout: modifications are written back to the caller's variable

func addBonus

(

_ score

:

inout Int

)

{

    score

=

10

}

var runoobScore

=

60

addBonus

(

&

runoobScore

)

print

(

"After adding points: (runoobScore)"

)

// In-place modification for structs as well

struct

RunoobCounter

{

    var count

=

0

    mutating func increase

(

)

{

        count

=

1

   

}

}

func increaseTwice

(

_ counter

:

inout RunoobCounter

)

{

    counter.

increase

(

)

    counter.

increase

(

)

}

var counter

=

RunoobCounter

(

)

increaseTwice

(

&

counter

)

print

(

"Count: (counter.count)"

)

Running the above code produces the following output:



加分后:70

计数:2

Exclusive access is the constraint imposed by inout: only one write access to a given piece of memory may occur at a time.

If you write to a variable while also reading it, Swift terminates the program at runtime because the outcome of such overlapping access is unpredictable.

Example

var stepSize

=

1

func increment

(

_ number

:

inout Int

)

{

    number

=

stepSize      

// Read a global variable

}

// Perform both a "write" (passed as inout) and a "read" on stepSize; runtime trap

increment

(

&

stepSize

)

Running this code terminates with a message similar to the following; the address differs each time:



Simultaneous accesses to 0x..., but modification requires exclusive access.

Passing the same variable as two inout parameters at once is an error detectable at compile time.

Example

func balance

(

_ x

:

inout Int, _ y

:

inout Int

)

{

    let total

=

x

y

    x

=

total

/

2

    y

=

total

x

}

var playerOneScore

=

42

var playerTwoScore

=

30

balance

(

&

playerOneScore,

&

playerTwoScore

)

 

// Two different variables, valid

print

(

"Player one: (playerOneScore), player two: (playerTwoScore)"

)

// balance(&playerOneScore, &playerOneScore) // Compile error: inout parameters cannot alias each other

Running the above code produces the following output:



玩家一:36,玩家二:36

Uncommenting that line produces a compile error:



error: inout arguments are not allowed to alias each other

In addition, while a struct's mutating method is running, the instance is in a state of exclusive access and cannot be accessed by other means during that time.


Common questions

The following questions arise most often when understanding value semantics.

Does assigning a struct always copy it?

Not necessarily. Copying is a semantic guarantee, but the compiler can optimize.

Types like Array that implement COW internally do not copy elements immediately on assignment; they copy only on write.

Why does modifying a copy of an array suddenly become slow?

Because that write triggers a real buffer copy.

With many copies and a large array, the cost of the first write is noticeable; later writes return to in-place modification since the buffer is now private.

Are value semantics and thread safety the same thing?

No. Value semantics means copies do not affect each other, but it does not mean shared reference types are thread-safe.

If a struct holds a mutable reference type internally, multiple copies still access the same object concurrently, so locks are still needed where appropriate.

When should you use class?

Use class when you need identity (distinguished with ===), need inheritance, or genuinely need to share the same mutable state.

In all other cases prefer struct, while keeping an eye on internal reference-type properties and adding COW to them when necessary.