Chapters

Hide chapters

Swift Apprentice: Beyond the Basics

First Edition · iOS 16 · Swift 5.8 · Xcode 14.3

Section I: Beyond the Basics

Section 1: 13 chapters
Show chapters Hide chapters

8. Value Types & Reference Types
Written by Ehab Amer

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Swift supports two kinds of types: value types and reference types. Structs and enums are value types, while classes and functions are reference types and differ in behavior. The behavior you’ve come to expect from value types results from value semantics. When a type supports value semantics, you can reason about a variable’s value by looking only at that variable since interactions with other variables cannot affect it.

Value semantics guarantees the independence of variables, which rules out a large class of bugs. This safety is why most Swift standard library types support value semantics, why many Cocoa types are imported to offer value semantics and why you should use value semantics when appropriate. Value semantics aren’t always the proper choice and require subtle handling to support correctly.

This chapter will define value semantics, show how to test for it and explain when it’s suitable. You’ll learn to build types with value semantics using value types, reference types or some mix of the two. You’ll learn how a deftly mixed type can offer the best of both worlds, with the simple interface of value semantics and the efficiency of reference types under the hood.

Value Types vs. Reference Types

Value and reference types differ in their assignment behavior, which is just a name for what Swift does whenever you assign a value to a variable. Assigning value is routine and happens every time you assign to global variables, local variables or properties. You also assign whenever you call a function, effectively assigning arguments to the function’s parameters.

Reference Types

Reference types use assign-by-reference. When a variable is of a reference type, assigning an instance to the variable sets that variable to refer to that instance. If another variable was already referring to that instance, then both variables post-assignment refer to the same instance, like so:

sav epovaR = Biqveq() dar baklQdeeN = ofoluC yutiohmuj uleduY epejoZ tullZsaaQ oqnkadrur

struct Color: CustomStringConvertible {
  var red, green, blue: Double
  
  var description: String {
    "r: \(red) g: \(green) b: \(blue)"
  }
}

// Preset colors
extension Color {
  static var black = Color(red: 0, green: 0, blue: 0)
  static var white = Color(red: 1, green: 1, blue: 1)
  static var blue  = Color(red: 0, green: 0, blue: 1)
  static var green = Color(red: 0, green: 1, blue: 0)
  // more ...
}

// Paint bucket abstraction
class Bucket {
  var color: Color
  var isRefilled = false
  
  init(color: Color) {
    self.color = color
  }
  
  func refill() {
    isRefilled = true
  }
}
let azurePaint = Bucket(color: .blue)
let wallBluePaint = azurePaint
wallBluePaint.isRefilled // => false, initially
azurePaint.refill()
wallBluePaint.isRefilled // => true, unsurprisingly!

Value Types

Value types, however, use assign-by-copy. Assigning an instance to a variable of a value type copies the instance and sets the variable to hold that new instance. So after every assignment, a variable contains an instance it owns all to itself.

hiz urajo = Yupoc.wfao // Kbetl uaqolixukaksr // xigeed zji ajpjapru jiquolrib uhexo ukoqa azbyuwpul cub kergMnee = awige urixo mepgTlai

extension Color {
  mutating func darken() {
    red *= 0.9; green *= 0.9; blue *= 0.9
  }
}

var azure = Color.blue
var wallBlue = azure
azure  // r: 0.0 g: 0.0 b: 1.0
wallBlue.darken()
azure  // r: 0.0 g: 0.0 b: 1.0 (unaffected)

Defining Value Semantics

What’s nice about primitive value types like Color or Int isn’t the assign-by-copy behavior itself but rather the guarantee this behavior creates.

var x = MysteryType()
var y = x
exposeValue(x) // => initial value derived from x
// {code here which uses only y}
exposeValue(x) // => final value derived from x
// Q: are the initial and final values different?

When to Prefer Value Semantics

When should you design a type to support value semantics? This choice depends on what your type is supposed to model.

Implementing Value Semantics

Now assume you do want value semantics. If you’re defining a type, how do you enforce it? The approach depends on the details of the type. In this section, you’ll consider the various cases one by one.

Case 1: Primitive Value Types

Primitive value types like Int support value semantics automatically. This support is because assign-by-copy ensures each variable holds its own instance — so no other variable can affect the instance — and because the instance itself is structurally independent. The instance defines its own value independently of any other instance so that no other instance could affect its value.

Case 2: Composite Value Types

Composite value types other than class, like a tuple, struct or enum, support value semantics if all the stored components support value semantics.

Case 3: Reference Types

Reference types can also have value semantics.

var a = UIImage(named:"smile.jpg")
var b = a
computeValue(b) // => something
doSomething(a)
computeValue(b) // => same thing!

Case 4: Value Types Containing Mutable Reference Types

The last case is mixed types: value types that contain mutable reference types. This case is the subtlest but perhaps the most valuable. It can provide a simple programming model of value semantics with the efficiency benefits of reference types. But it can easily fail to do so.

struct PaintingPlan { // a value type, containing ...
  // a value type
  var accent = Color.white
  // a mutable reference type
  var bucket = Bucket(color: .blue)
}
let artPlan = PaintingPlan()
let housePlan = artPlan
artPlan.bucket.color // => blue
// for house painting only, we fill the bucket with green paint
housePlan.bucket.color = Color.green
artPlan.bucket.color // => green. oops!
dsahixbeer zoeqeBpey kobeoswep (mek-yebah) asdudn vasrim lkutaygeuq ehzuxz besbuk otwVveb

Copy-on-Write to the Rescue

What’s the fix? The first step is recognizing that value semantics are defined relative to an access level. Value semantics depend on what changes you can make and see with a variable, depending on the setters’ access level and mutating functions of the variable’s type.

struct PaintingPlan { // a value type, containing ...
  // a value type
  var accent = Color.white
  // a private reference type for "deep storage"
  private var bucket = Bucket()

  // a pseudo-value type, using the deep storage
  var bucketColor: Color {
    get {
      bucket.color
    }
    set {
      bucket = Bucket(color: newValue)
    }
  }
}
struct PaintingPlan { // a value type, containing ...
  // ... as above ...

  // a computed property facade over deep storage
  // with copy-on-write and in-place mutation when possible
  var bucketColor: Color {
    get {
      bucket.color
    }
    set {
      if isKnownUniquelyReferenced(&bucket) {
        bucket.color = bucketColor
      } else {
        bucket = Bucket(color: newValue)
      }
    }
  }
}

Recipes for Value Semantics

To summarize, here is the recipe for determining if a type has value semantics or for defining your own such type:

Sidebar: Sendable

While the benefits of value semantics may seem subtle, the recipe above is fairly simple at the end of the day. The recipe is so simple that you might wonder: couldn’t the compiler lend a hand?

Challenges

Before moving on, here are some challenges to test your knowledge of value types, reference types, and value semantics. It’s best to try to solve them yourself, but solutions are available if you get stuck.

Challenge 1: Image with Value Semantics

Build a new type, Image, representing a simple image. It should also provide mutating functions that apply modifications to the image. Use copy-on-write to economize memory use when a user defines a large array of these identical images and doesn’t mutate any of them.

private class Pixels {
  let storageBuffer: UnsafeMutableBufferPointer<UInt8>

  init(size: Int, value: UInt8) {
    let p = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
    storageBuffer = UnsafeMutableBufferPointer<UInt8>(start: p, count: size)
    storageBuffer.initialize(from: repeatElement(value, count: size))
  }

  init(pixels: Pixels) {
    let otherStorage = pixels.storageBuffer
    let p  = UnsafeMutablePointer<UInt8>.allocate(capacity: otherStorage.count)
    storageBuffer = UnsafeMutableBufferPointer<UInt8>(start: p, count: otherStorage.count)
    storageBuffer.initialize(from: otherStorage)
  }
  
  subscript(offset: Int) -> UInt8 {
    get {
      storageBuffer[offset]
    }
    set {
      storageBuffer[offset] = newValue
    }
  }
  
  deinit {
    storageBuffer.baseAddress!.deallocate(capacity: self.storageBuffer.count)
  }
}
var image1 = Image(width: 4, height: 4, value: 0)

// test setting and getting
image1[0,0] // -> 0 
image1[0,0] = 100
image1[0,0] // -> 100
image1[1,1] // -> 0

// copy
var image2 = image1
image2[0,0] // -> 100
image1[0,0] = 2
image1[0,0] // -> 2
image2[0,0] // -> 100 because of copy-on-write

var image3 = image2
image3.clear(with: 255)
image3[0,0] // -> 255
image2[0,0] // -> 100 thanks again, copy-on-write

Challenge 2: Enhancing UIImage

Pretend you’re Apple and want to modify UIImage to replace it with a value type with the mutating functions described above. Could you make it backward compatible with code that uses the existing UIImage API?

Challenge 3: Determining if a Type Has Value Semantics

Consider the test snippet used to determine if a type has value semantics. How do you define an automatic means to test if a type supports value semantics? If I handed you a type, can you tell me if it offers value semantics? What if you could not see its implementation? Could the compiler be expected to know?

Key Points

Where to Go From Here?

The best place to explore advanced implementations of value semantic types is in the Swift standard library, which relies extensively on these optimizations.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now