Dice Foundry Quick Reference

Swift and SwiftUI Quick Reference

This guide is a compact companion to the Dice Foundry course. Keep it open beside Xcode while you work. It summarizes the Swift language features and SwiftUI tools you meet in the course, plus a set of closely related topics you will see in other projects and in AI-generated code.

How to use this guide

Each concept follows the same pattern so you can scan it quickly:

  • Purpose — what the feature is for, in one or two sentences.
  • Syntax — the common forms you will type or read.
  • Example — a short example, using Dice Foundry names where possible.
  • Course chapter — where Dice Foundry teaches the concept, so you can return to the full explanation.

Topics that are useful to know but not required to complete Dice Foundry are marked with a callout like this one:

Note: Beyond Dice Foundry

This topic is included for future reference. You do not need it to finish the course project, but you will meet it in other apps, in Apple sample code, and in AI-generated Swift.

A few more conventions:

  • All examples are illustrative (swift-example). They are written to be correct Swift, but they are not copied line for line from the project. For the exact project code, use the reference checkpoints and the workbook chapters.
  • The toolchain assumed throughout is Xcode 27.2, Swift 6.4 compiler in Swift 5 language mode, and an iOS 17.0 minimum deployment target. Every API in this guide is available on iOS 17 unless it is explicitly labeled with a later version.
  • Where Xcode menu names or exact compiler wording might differ in your version, the guide says so. Treat quoted messages as "similar to" what you will see.
  • The worked example used throughout is the course's standard roll: a D6, quantity 3, modifier +2, dice 4, 2 and 6. The notation is 3D6 + 2, the subtotal is 12, and the total is 14.

Swift Language Basics

Variables and Constants

Purpose: Name a value so you can use it later. let declares a constant that cannot change after it is set; var declares a variable that can. Prefer let and switch to var only when the value really needs to change. The compiler warns you when a var is never changed.

Syntax:

Example — not part of the Dice Foundry project
let name = value             // constant, type inferred
var name = value             // variable, type inferred
let name: Type = value       // constant with a type annotation
var name: Type               // declared now, assigned before first use

Example:

Example — not part of the Dice Foundry project
let maximumHistory = 50      // never changes
var quantity = 3             // changes when the user taps the stepper
quantity += 1                // quantity is now 4

let modifier: Int = 2        // explicit type annotation
var rolledTotal: Int         // declared without a value
rolledTotal = 14             // initialized before it is read

Key points:

  • Type inference: Swift works out the type from the initial value. let quantity = 3 is an Int. Add an annotation when the inferred type would be wrong or when you want to make intent clear.
  • Declare, initialize, assign, read: a value must be initialized before it is read. The compiler enforces this.
  • Scope: a name exists only inside the braces { } where it is declared. A let inside a function disappears when the function returns.
  • Naming: use lowerCamelCase for variables, constants, and functions (selectedDie, rollCount), and UpperCamelCase for types (RollResult, DieType).
Infrastructure Analogy

A let is like a read-only configuration value set at deploy time; a var is a value your automation is allowed to update while it runs.

Course chapter: Chapter 2 (Swift fundamentals). Properties inside types are covered in Chapter 8.

Basic Data Types

Purpose: Every value in Swift has a type that decides what it can hold and which operations are allowed. Swift never converts between types silently; you convert explicitly.

Syntax:

Type Holds Literal examples
Int Whole numbers (64-bit on all current iPhones) 0, 14, -4
Double Decimal numbers (64-bit floating point) 3.5, 0.6, -1.0
Bool true or false true
String Text "Dice Foundry"
Character A single character "D" (with a Character annotation)
CGFloat Graphics measurement used by some SwiftUI APIs 16 (in a CGFloat context)
UUID A unique identifier (Foundation) UUID()
Date A point in time (Foundation) Date() (now)
URL A file or web location (Foundation) URL.documentsDirectory

Example:

Example — not part of the Dice Foundry project
let sides: Int = 6
let average: Double = 3.5
let hapticsEnabled: Bool = true
let title: String = "Dice Foundry"

// Conversion is always explicit
let rolls = 4
let total = 14
let mean = Double(total) / Double(rolls)    // 3.5
let whole = Int(3.9)                        // 3 (truncates toward zero)
let text = String(total)                    // "14"
let parsed = Int("12")                      // Int? — 12, or nil if not a number

Key points:

  • Int("12") returns an optional (Int?) because the text might not be a number. See Optionals below.
  • Mixing Int and Double in one expression is a compiler error: convert one side first.
  • CGFloat and Double convert implicitly in most SwiftUI code since Swift 5.5, so Theme.cornerRadius: CGFloat = 16 and a Double literal usually work together.

Course chapter: Chapter 2. UUID and Date arrive in Chapter 8; URL in Chapter 9; CGFloat in Chapter 11.

Operators

Purpose: Combine and compare values. Swift operators are type-checked: both sides of + must be the same type.

Syntax:

Category Operator Meaning Example Result
Arithmetic + - * / Add, subtract, multiply, divide 12 + 2 14
Arithmetic % Remainder (integers) 14 % 6 2
Integer division / on Int Discards the fraction 7 / 2 3
Unary minus - Negate -modifier -2
Assignment = Store a value quantity = 3
Compound += -= *= /= Update in place rollCount += 1
Comparison == != Equal, not equal selectedDie == .d6 true
Comparison < > <= >= Ordering modifier > 0 true
Logical && AND quantity >= 1 && quantity <= 10 true
Logical \|\| OR modifier < -20 \|\| modifier > 20 false
Logical ! NOT !history.isEmpty
Ternary ? : Choose one of two values isSelected ? Theme.brass : .gray
Nil-coalescing ?? Value or fallback latestRoll?.total ?? 0
Closed range ... Includes both ends 1...6 1 to 6
Half-open range ..< Excludes the upper end 0..<3 0, 1, 2
One-sided range 1... From 1 upward case 1...:
Identity === !== Same class instance a === b

Example:

Example — not part of the Dice Foundry project
let values = [4, 2, 6]
let modifier = 2
let subtotal = values[0] + values[1] + values[2]   // 12
let total = subtotal + modifier                    // 14

let isValidQuantity = values.count >= 1 && values.count <= 10   // true
let label = modifier > 0 ? "+\(modifier)" : "\(modifier)"       // "+2"
let magnitude = abs(-4)                                          // 4

Key points:

  • = assigns; == compares. Using = inside an if condition is a compiler error in Swift, which catches a classic bug.
  • Integer overflow traps at runtime instead of wrapping silently.
  • min(a, b) and max(a, b) are functions, not operators; Dice Foundry uses them to clamp the quantity.

Course chapter: Chapter 2 (arithmetic, comparison, assignment, compound). Logical operators in Chapter 7. Ternary in Chapter 5. Ranges in Chapters 4 and 6. min/max in Chapter 12.

Strings and Interpolation

Purpose: Store and build text. Interpolation, written \( ), inserts any value into a string literal and is how most Dice Foundry labels are built.

Syntax:

Example — not part of the Dice Foundry project
let literal = "plain text"
let interpolated = "Total: \(expression)"
let multiline = """
    Line one
    Line two
    """
let joined = first + " " + second

Example:

Example — not part of the Dice Foundry project
let quantity = 3
let dieName = "D6"
let modifier = 2

let dice = "\(quantity)\(dieName)"            // "3D6"
let notation = "\(dice) + \(modifier)"        // "3D6 + 2"
let caption = "Total \(12 + modifier)"        // "Total 14"

let values = [4, 2, 6]
let description = values.map { String($0) }.joined(separator: ", ")   // "4, 2, 6"

Common operations:

Task Code Result
Length "D20".count 3
Empty check "".isEmpty true
Case "history".uppercased() "HISTORY"
Contains "3D6 + 2".contains("+") true
Prefix "D20".hasPrefix("D") true
Split "4, 2, 6".split(separator: ", ") ["4", "2", "6"] (substrings)
Convert to Int Int("12") Optional(12)
Trim (Foundation) " d6 ".trimmingCharacters(in: .whitespaces) "d6"

Key points:

  • Interpolation calls the value's text description, so "\(roll.total)" works for numbers, Booleans, and enums.
  • In SwiftUI, Text("Total \(roll.total)") uses interpolation directly; you do not need to build a String first.
  • Strings are value types: copying a string and changing the copy never changes the original.
  • Swift strings are Unicode-correct, so you cannot index them with an integer like text[0]. Use first, prefix(_:), or convert to an array if you really need positions.

Course chapter: Chapter 2 (interpolation). map and joined in Chapter 8. Date formatting in Chapter 8.

Conditionals

Purpose: Run different code depending on a condition. Swift has if/else if/else, switch, the ternary operator, and guard.

Syntax:

Example — not part of the Dice Foundry project
if condition {
    // runs when condition is true
} else if otherCondition {
    // runs when the first is false and this is true
} else {
    // runs otherwise
}

switch value {
case pattern1:
    // ...
case pattern2, pattern3:
    // ...
default:
    // ...
}

Example:

Example — not part of the Dice Foundry project
func notation(quantity: Int, dieName: String, modifier: Int) -> String {
    let dice = "\(quantity)\(dieName)"
    if modifier > 0 {
        return "\(dice) + \(modifier)"
    } else if modifier < 0 {
        return "\(dice) - \(abs(modifier))"
    } else {
        return dice
    }
}

func formatModifier(_ value: Int) -> String {
    switch value {
    case 0:
        return "0"
    case 1...:
        return "+\(value)"
    default:
        return "\(value)"
    }
}

Key points:

  • Conditions must be Bool. Swift does not treat 0 or nil as false.
  • switch must be exhaustive: every possible value must match some case. Use default for "everything else". Switching over an enum with every case listed needs no default.
  • Cases do not fall through to the next case, so there is no break at the end of each case.
  • In SwiftUI, an if inside body shows or hides views: if history.isEmpty { Text("No rolls yet") }.
  • Since Swift 5.9, if and switch can be used as expressions: let label = if modifier > 0 { "positive" } else { "not positive" }. You will see this in newer code; Dice Foundry uses the statement form.

guard

Note: Beyond Dice Foundry

Dice Foundry mentions guard for recognition only and does not use it. AI-generated code uses it heavily, so you should be able to read it. guard checks a condition and must leave the current scope (with return, throw, break or continue) when the condition is false. It keeps the "happy path" unindented.

Example — not part of the Dice Foundry project
func load() throws -> [RollResult] {
    guard FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) else {
        return []                       // early exit
    }
    let data = try Data(contentsOf: fileURL)
    return try JSONDecoder().decode([RollResult].self, from: data)
}

Dice Foundry's HistoryStore.load() writes the same check as if !FileManager.default.fileExists(...) { return [] }. The two forms are equivalent here.

switch with associated values and where clauses

Note: Beyond Dice Foundry

Dice Foundry switches on simple enum cases and integer ranges. Enums with associated values and where clauses are common elsewhere.

Example — not part of the Dice Foundry project
enum LoadState {
    case idle
    case loaded(count: Int)
    case failed(message: String)
}

func summary(for state: LoadState) -> String {
    switch state {
    case .idle:
        return "Not loaded"
    case .loaded(let count) where count == 0:
        return "No rolls yet"
    case .loaded(let count):
        return "\(count) rolls"
    case .failed(let message):
        return "Error: \(message)"
    }
}

Course chapter: Chapter 7 (if/else if/else, switch with ranges and default, conditional views). switch self on an enum in Chapter 11. guard recognition in Chapter 9.

Loops

Purpose: Repeat work. Swift's main loop is for ... in, which walks through a range or a collection. while repeats until a condition becomes false.

Syntax:

Example — not part of the Dice Foundry project
for item in collection { }
for number in 1...6 { }          // 1 through 6
for index in 0..<count { }       // 0 through count - 1
for _ in 1...3 { }               // repeat 3 times, ignore the counter
while condition { }
repeat { } while condition       // runs at least once

Example:

Example — not part of the Dice Foundry project
// Roll three D6 (as DiceRoller does)
var values: [Int] = []
for _ in 1...3 {
    values.append(Int.random(in: 1...6))
}

// Sum with a loop...
var sum = 0
for value in values {
    sum += value
}

// ...or with reduce (what the project uses)
let subtotal = values.reduce(0, +)

// Index and value together
for (index, value) in values.enumerated() {
    print("Die \(index + 1): \(value)")
}

Key points:

  • _ means "I do not need this value". Use it for the loop counter when you only care about repetition.
  • 1...count crashes if count is less than 1, because a range's lower bound cannot exceed its upper bound. Dice Foundry clamps the quantity before looping for this reason.
  • break exits a loop; continue skips to the next iteration.
  • In SwiftUI, you do not write for loops inside body. Use ForEach, which builds one view per element (see Lists and Grids).

Course chapter: Chapter 6 (for ... in, _, ranges, summing with a loop, reduce).

Collections

Arrays

Purpose: An ordered list of values of one type. Dice Foundry stores rolled values in [Int] and the roll history in [RollResult].

Syntax:

Example — not part of the Dice Foundry project
var name: [Type] = []                 // empty array
let name = [value1, value2, value3]   // array literal, type inferred
name[index]                           // read by position (0-based)
name.append(value)
name.insert(value, at: index)
name.remove(at: index)
name.removeLast()
name.removeAll()

Example:

Example — not part of the Dice Foundry project
var history: [RollResult] = []
let roll = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)

history.insert(roll, at: 0)          // newest first
if history.count > 50 {
    history.removeLast()             // trim the oldest
}

let values = [4, 2, 6]
values.count                         // 3
values.isEmpty                       // false
values[0]                            // 4
values.first                         // Optional(4)
values.last                          // Optional(6)
values.contains(6)                   // true
values.indices                       // 0..<3

Useful higher-order methods (they take a closure; see Closures):

Method Purpose Example Result
map Transform each element values.map { $0 * 2 } [8, 4, 12]
filter Keep matching elements values.filter { $0 > 3 } [4, 6]
reduce Combine into one value values.reduce(0, +) 12
sorted Return a sorted copy values.sorted() [2, 4, 6]
contains(where:) Any element matches? values.contains { $0 == 6 } true
allSatisfy Every element matches? values.allSatisfy { $0 >= 1 } true
first(where:) First match, optional values.first { $0 > 4 } Optional(6)
compactMap Transform and drop nil ["4", "x"].compactMap { Int($0) } [4]
max() / min() Largest or smallest, optional values.max() Optional(6)
joined(separator:) Join strings ["4", "2"].joined(separator: ", ") "4, 2"

Key points:

  • Indexing past the end (values[3] on a three-element array) is a runtime crash: "Index out of range". Check indices or count first, or use first/last, which return optionals.
  • Arrays are value types. var copy = history makes an independent copy; changing copy never changes history.
  • A let array cannot be changed at all: no append, no remove.

Course chapter: Chapter 6 (literals, append, indexing, isEmpty, count, reduce, indices). insert(at:), map, joined and arrays of structs in Chapter 8. removeLast() in Chapter 9. filter, $0 and allSatisfy appear only in Chapter 14 hints.

Dictionaries

Note: Beyond Dice Foundry

Dice Foundry does not use dictionaries. They are one of the most common collections in Swift, especially for lookups, counting, and decoding JSON, so you will meet them quickly in other projects.

Purpose: An unordered collection of key-value pairs, where each key is unique. Looking up a key returns an optional, because the key might not be present.

Syntax:

Example — not part of the Dice Foundry project
var name: [KeyType: ValueType] = [:]          // empty dictionary
let name = ["key1": value1, "key2": value2]   // literal
name[key]                                     // read: returns ValueType?
name[key] = value                             // insert or replace
name[key] = nil                               // remove
name[key, default: fallback]                  // read with a default

Example:

Example — not part of the Dice Foundry project
// Count how often each die type was rolled
var rollsPerDie: [DieType: Int] = [:]
for roll in history {
    rollsPerDie[roll.dieType, default: 0] += 1
}

let d6Count = rollsPerDie[.d6] ?? 0          // optional lookup with fallback

for (dieType, count) in rollsPerDie {
    print("\(dieType.name): \(count)")       // order is not guaranteed
}

let sortedKeys = rollsPerDie.keys.sorted { $0.sides < $1.sides }
let grouped = Dictionary(grouping: history, by: { $0.dieType })   // [DieType: [RollResult]]

Key points:

  • Keys must be Hashable. String, Int, UUID, and enums without associated values are all hashable. DieType is hashable automatically because it has a raw value.
  • Iteration order is not stable. Sort the keys if you display them.
  • A Set<Type> is the related collection for unique values with no keys: var favorites: Set<DieType> = [.d6, .d20].

Course chapter: Not taught in Dice Foundry.

Functions and Closures

Functions

Purpose: Package a named, reusable piece of work that can take inputs (parameters) and produce an output (a return value).

Syntax:

Example — not part of the Dice Foundry project
func name(label parameterName: Type, other: Type = defaultValue) -> ReturnType {
    // body
    return value
}

func name(_ parameterName: Type) { }     // no argument label at the call site

Example:

Example — not part of the Dice Foundry project
func rollDie(sides: Int) -> Int {
    Int.random(in: 1...sides)          // single expression: return is implicit
}

func roll(_ dieType: DieType, quantity: Int, modifier: Int = 0) -> RollResult {
    var values: [Int] = []
    for _ in 1...quantity {
        values.append(rollDie(sides: dieType.sides))
    }
    return RollResult(dieType: dieType, values: values, modifier: modifier)
}

let single = rollDie(sides: 20)
let result = roll(.d6, quantity: 3, modifier: 2)
let plain = roll(.d8, quantity: 1)      // modifier uses its default value

Key points:

  • Argument labels: each parameter can have an external label (used by the caller) and an internal name (used in the body). func roll(_ dieType: ...) uses _ to remove the label, so you call roll(.d6, ...). Labels make call sites read like sentences: history.insert(roll, at: 0).
  • Return type: -> Int declares what comes back. No arrow means the function returns nothing (Void).
  • Implicit return: a body that is a single expression returns that expression without return. This is why computed properties and body often have no return.
  • Parameters are constants. Copy into a local var if you need to change one.
  • Unused results: calling a function and ignoring its return value produces a warning. Write _ = roller.roll(...) to discard it deliberately.
  • Methods: a function declared inside a type is called a method. Methods on a struct that change its stored properties must be marked mutating.
  • static func belongs to the type itself, not an instance: RollResult.formatModifier(2).

Course chapter: Chapter 4 (functions, parameters, labels, return values). Default parameter values in Chapter 8. static in Chapter 9 and Chapter 10. _ = in Chapter 12.

Closures

Purpose: A closure is a block of code you can store in a variable or pass as an argument, to run later. Button actions, ForEach content, map, reduce, sorted, and Dice Foundry's injectable random source are all closures.

Syntax:

Example — not part of the Dice Foundry project
{ (parameters) -> ReturnType in
    statements
}

let name: (ParameterTypes) -> ReturnType = { parameters in ... }

// Trailing closure: the final closure argument moves outside the parentheses
function(argument) { closure body }

Example:

Example — not part of the Dice Foundry project
// A stored closure (the shape DiceRoller uses)
var randomValue: (ClosedRange<Int>) -> Int = { range in
    Int.random(in: range)
}
let value = randomValue(1...6)

// A test replaces it with a predictable closure
let alwaysFour: (ClosedRange<Int>) -> Int = { _ in 4 }

// A closure-typed property in a view (DieButton's action)
struct DieButton: View {
    let dieType: DieType
    let action: () -> Void
    var body: some View {
        Button(dieType.name, action: action)
    }
}

// Shorthand forms, from longest to shortest
let doubled1 = [4, 2, 6].map({ (value: Int) -> Int in return value * 2 })
let doubled2 = [4, 2, 6].map { value in value * 2 }
let doubled3 = [4, 2, 6].map { $0 * 2 }          // $0 is the first argument

let newestFirst = history.sorted { $0.date > $1.date }

Multiple trailing closures, as in SwiftUI's Button:

Example — not part of the Dice Foundry project
Button {
    viewModel.roll()             // first closure: the action
} label: {
    Label("Roll Dice", systemImage: "dice.fill")   // labeled second closure
}

Key points:

  • () -> Void is the type "takes nothing, returns nothing". Read (ClosedRange<Int>) -> Int as "takes a closed range of integers, returns an integer".
  • in separates the parameter list from the body.
  • $0, $1 are automatic names for the first and second parameters. They keep short closures short; use named parameters when the closure is longer than a line or two.
  • Closures capture the variables they use. A closure that outlives the current function call is called escaping; in class-based code you will see [weak self] in a capture list to avoid a retain cycle. Dice Foundry does not need this.
  • Operators are functions, so reduce(0, +) passes the + operator as the combining closure.

Course chapter: Chapter 4 (a button action is a closure, trailing closure syntax previewed in Chapter 3). Multiple trailing closures in Chapter 5. reduce in Chapter 6. map in Chapter 8. Closure-typed properties () -> Void in Chapter 10. Stored closures for dependency injection in Chapter 12. $0 shorthand appears in Chapter 14 hints.

async and await

Note: Beyond Dice Foundry

Dice Foundry does all its work synchronously: rolling dice and saving a small JSON file are fast. Networking, large file work, and many Apple APIs are asynchronous, so you will see async/await in almost every other app.

Purpose: Run work that takes time (a network request, a large read) without freezing the interface. An async function can pause at each await and resume later.

Syntax:

Example — not part of the Dice Foundry project
func name() async throws -> ReturnType { }
let value = try await name()
Task { await doSomething() }                 // start async work from sync code
.task { await loadSomething() }              // SwiftUI: runs when the view appears

Example:

Example — not part of the Dice Foundry project
struct RemoteRollService {
    func fetchDailyChallenge() async throws -> String {
        let url = URL(string: "https://example.com/challenge.txt")!
        let (data, _) = try await URLSession.shared.data(from: url)
        return String(decoding: data, as: UTF8.self)
    }
}

struct ChallengeView: View {
    @State private var challenge = "Loading..."
    let service = RemoteRollService()

    var body: some View {
        Text(challenge)
            .task {
                do {
                    challenge = try await service.fetchDailyChallenge()
                } catch {
                    challenge = "Could not load the challenge."
                }
            }
    }
}

Key points:

  • .task is cancelled automatically when the view disappears.
  • In the Xcode 27.2 app template, app code runs on the main actor (the main thread) by default. SwiftUI state must be updated on the main actor, which this default makes simple. Chapter 13 introduces the main actor at an introductory level.

Course chapter: Not taught in Dice Foundry. The main actor default is introduced in Chapter 13.