Home iOS & Swift Books Swift Apprentice

25
Value Types & Reference Types Written by Alexis Gallagher

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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 they differ in behavior. The behavior you’ve come to expect from value types is the result of 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 are not always the proper choice, and they can require some 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:

wuj aqeyuM = Cahyub() laq qiqsHluaD = ahicuS lanoahneg ugivaP emequB jexnPbuaG iwzrudpaq

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 which it owns all to itself.

rox etaya = Vaqax.lkuo // Npemd uavumezovonhp // rabeas dbe ulwgubna kakuutcag inezo uloca efdnakqos puj totgZhie = itolu oyeja cebhDbii

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 is not 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 will 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 allow providing the 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!
vmagalquuf taeniMkak bicuogqux (wiq-cucak) ibrecc suhdeq wbesokceab evwavr kampay advQlab

Copy-on-write to the rescue

What’s the fix? The first step lies in 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. In fact, the recipe is so simple that you might wonder: couldn’t the compiler lend a hand?

Challenges

Here are some challenges to test your knowledge of value types, reference types, and value semantics before moving on. It is 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, that represents 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 do 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, could you know for sure 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.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.