Swift Academy · Lesson

Layout Cache and Performance

Use the layout cache for efficiency.

Lesson 4 of 413 steps

Layout Cache and Performance is a free Swift Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

Why a Layout Cache?

SwiftUI may call sizeThatFits and placeSubviews many times during a single layout pass.

If your calculations are expensive, a cache lets you compute once and reuse, avoiding repeated work.

The Cache Associated Type

The Layout protocol has an associated Cache type, defaulting to Void. Define your own struct to store precomputed results.

struct FlowLayout: Layout {
    struct CacheData {
        var sizes: [CGSize] = []
    }
    typealias Cache = CacheData
}

makeCache

Implement makeCache(subviews:) to build the initial cache. SwiftUI calls it once before the layout methods, giving you a place to do up-front measurement.

func makeCache(subviews: Subviews) -> CacheData {
    let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
    return CacheData(sizes: sizes)
}

Reading the Cache

The layout methods now receive cache as an inout parameter. Read your precomputed values instead of re-measuring every child.

func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout CacheData) -> CGSize {
    let height = cache.sizes.map(\.height).max() ?? 0
    let width = cache.sizes.reduce(0) { $0 + $1.width }
    return CGSize(width: width, height: height)
}

updateCache

When the set of subviews changes, SwiftUI calls updateCache(_:subviews:). The default implementation rebuilds via makeCache, but you can override it to update incrementally.

func updateCache(_ cache: inout CacheData, subviews: Subviews) {
    cache.sizes = subviews.map { $0.sizeThatFits(.unspecified) }
}

When updateCache Fires

updateCache runs when subview count or identity changes—not on every geometry tweak. Cache only data that depends on the subviews, not on the proposed size.

Cache Only Proposal-Independent Data

A common bug is caching results that depend on the proposed size. The proposal can change between calls, so size-dependent results must be recomputed, not cached blindly.

// OK to cache: intrinsic child sizes
// NOT OK to cache: row breaks (depend on proposed width)

Caching Intrinsic Sizes

The safe pattern is to cache the expensive sizeThatFits(.unspecified) results, then run the cheap wrapping arithmetic per call using the current proposal.

struct CacheData { var intrinsic: [CGSize] = [] }
// wrapping uses cache.intrinsic + current maxWidth

Avoid Premature Optimization

For a handful of simple children, measurement is cheap and a cache adds complexity. Profile first; reach for a cache only when measurement is genuinely costly (text, images, nested layouts).

Cache and Value Semantics

The cache is owned by SwiftUI, passed inout. Keep it a plain value type with no references to views, so SwiftUI can manage its lifetime safely.

struct CacheData {
    var sizes: [CGSize] // value types only
}

Measuring the Win

Use the SwiftUI Instrument or simple counters to confirm the cache actually reduces measurement calls. Optimization without measurement is guesswork.

Quick Check: Layout Cache

Test your understanding of layout caching.

Recap: Layout Cache and Performance

The Layout protocol’s Cache associated type, built by makeCache and refreshed by updateCache, stores expensive proposal-independent work like intrinsic child sizes.

Run cheap, proposal-dependent arithmetic per call. Keep the cache a reference-free value type, avoid premature caching, and verify the benefit with profiling before adding complexity.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Layout Cache and Performance” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Layout Cache and Performance”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Layout Cache and Performance”?

Use the layout cache for efficiency. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Layout Cache and Performance” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Layout Protocol Basics
  2. Measuring Subviews
  3. Building a Flow Layout
  4. Layout Cache and Performance
← Back to Swift Academy