Structs group related values into one named type with stored properties.

Group related values

pageCount
struct_properties.swift
Replay: real traced execution (multi-file project)
struct Book {
    let title: String
    let pages: Int
}

let pageCount = 120
let book = Book(title: "Swift Notes", pages: pageCount)
let summary = "\(book.title): \(book.pages)"

print(summary)
struct Book {
    let title: String
    let pages: Int
}

let pageCount = 80
let book = Book(title: "Swift Notes", pages: pageCount)
let summary = "\(book.title): \(book.pages)"

print(summary)
struct Book {
    let title: String
    let pages: Int
}

let pageCount = 240
let book = Book(title: "Swift Notes", pages: pageCount)
let summary = "\(book.title): \(book.pages)"

print(summary)
  1. pageCount ← 120, book ← Book(title: "Swift Notes", pages: 120)

    6let pageCount→ 120 = 120  //@pageCount=80, 2407let book→ Book(title: "Swift Notes", pages: 120) = Book(title: "Swift Notes", pages: pageCount120)8let summary→ Swift Notes: 120 = "\(book.titleSwift Notes): \(book.pages120)"910print(summarySwift Notes: 120)
    outputSwift Notes: 120
  1. pageCount ← 80, book ← Book(title: "Swift Notes", pages: 80), summary ← Swift Notes: 80

    6let pageCount→ 80 = 807let book→ Book(title: "Swift Notes", pages: 80) = Book(title: "Swift Notes", pages: pageCount80)8let summary→ Swift Notes: 80 = "\(book.titleSwift Notes): \(book.pages80)"910print(summarySwift Notes: 80)
    outputSwift Notes: 80
  1. pageCount ← 240, book ← Book(title: "Swift Notes", pages: 240)

    6let pageCount→ 240 = 2407let book→ Book(title: "Swift Notes", pages: 240) = Book(title: "Swift Notes", pages: pageCount240)8let summary→ Swift Notes: 240 = "\(book.titleSwift Notes): \(book.pages240)"910print(summarySwift Notes: 240)
    outputSwift Notes: 240

Follow the Properties

  1. pageCount starts as 120.
  2. Book(title: "Swift Notes", pages: pageCount) creates one Book.
  3. book.title reads Swift Notes.
  4. book.pages reads 120.
  5. summary becomes Swift Notes: 120. | property | value | | --- | --- | | book.title | Swift Notes | | book.pages | 120 | | summary | Swift Notes: 120 |
structs A struct instance stores each property value together. Dot syntax reads the stored properties from that instance.

Exercise: struct_properties.swift

Reproduce Swift Notes: 120, then use the pinned pageCount variants 80 and 240 to predict Swift Notes: 80 and Swift Notes: 240.