02 Value & Reference Semantics

3 阅读1分钟

Value & Reference Semantics

Core Idea

The important distinction is not simply where something is stored in memory.

The key question is:

What happens when a value is copied?

Value Semantics

A copy represents an independent value.

Common examples:

  • struct
  • enum
  • Array
  • Dictionary
  • Set
  • String

Conceptually:

a
 ↓ copy
b

a and b represent independent values

Reference Semantics

A copy can refer to the same underlying instance.

Example:

let a = MyClass()
let b = a

Conceptually:

a ──┐
    ├──> same instance
b ──┘

Important

Do not use:

struct = stack

class = heap

as the primary model.

Storage and semantics are different layers.

Copy-on-Write

Some Swift value types can provide value semantics while sharing storage internally until mutation occurs.

Common examples:

  • Array

  • Dictionary

  • Set

  • String

Related