skip to content

In a custom SwiftUI Layout, when do makeCache and updateCache run, and what is safe to keep in the layout cache?

level: seniorimportance: nice to knowfreq 20%

answer

  1. shared inout storage
  2. built from subviews only
  3. default update just rebuilds
  4. no proposal in makeCache
  5. profile before caching

basics

~10 s

makeCache(subviews:) builds storage that a layout's methods receive inout; SwiftUI calls updateCache(_:subviews:) when the subviews change, and its default rebuilds through makeCache. Keep subview-derived measurements there and key anything that depends on the proposal.

solid answer

~40 s

The `Layout` protocol declares `associatedtype Cache = Void`. If you name your own `Cache` type you implement `makeCache(subviews:)`, and SwiftUI passes the value `inout` to `sizeThatFits`, `placeSubviews`, `spacing` and `explicitAlignment`, so they can share work. Apple's docs say SwiftUI calls `updateCache(_:subviews:)` if the subviews change, and the default implementation simply calls `makeCache` again. What belongs there is data derived from the subviews, such as each chip's ideal size. `makeCache` never receives a proposal, yet `sizeThatFits` can be asked about several, so row breaks must be recomputed per call or stored keyed by width. Treat the cache as disposable derived data, not state, and heed Apple's note that most simple layouts gain little from one: profile with Instruments first.

code

swift · 43 lines
swift
import SwiftUI

struct CachedFlowLayout: Layout {
    var spacing: CGFloat = 8

    struct Cache {
        var sizes: [CGSize]
    }

    // Required once Cache is not Void. The default updateCache(_:subviews:) calls this again.
    func makeCache(subviews: Subviews) -> Cache {
        Cache(sizes: subviews.map { $0.sizeThatFits(.unspecified) })
    }

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) -> CGSize {
        let frames = rowFrames(cache.sizes, maxWidth: proposal.width ?? .infinity)
        return CGSize(width: frames.map(\.maxX).max() ?? 0, height: frames.map(\.maxY).max() ?? 0)
    }

    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) {
        for (index, frame) in rowFrames(cache.sizes, maxWidth: bounds.width).enumerated() {
            subviews[index].place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY),
                                  proposal: ProposedViewSize(frame.size))
        }
    }

    // Row breaks depend on the width, so they are recomputed per call, never cached.
    private func rowFrames(_ sizes: [CGSize], maxWidth: CGFloat) -> [CGRect] {
        var frames: [CGRect] = []
        var origin = CGPoint.zero
        var rowHeight: CGFloat = 0
        for size in sizes {
            if origin.x > 0, origin.x + size.width > maxWidth {
                origin = CGPoint(x: 0, y: origin.y + rowHeight + spacing)
                rowHeight = 0
            }
            frames.append(CGRect(origin: origin, size: size))
            origin.x += size.width + spacing
            rowHeight = max(rowHeight, size.height)
        }
        return frames
    }
}

go deeper

for a junior

Recall that a Layout can share computed values between its methods through an optional cache whose type defaults to Void.

for a middle

Explain makeCache building the value, the inout cache parameter on each method, and the default updateCache calling makeCache again.

for a senior

Show you cache only subview-derived measurements, key proposal-dependent results, and profile with Instruments before adding a cache at all.

for a principal

Set a team rule that layouts start uncached and earn a cache with a measurement, keeping shared components simple to review.

## Why a layout has a cache at all A custom `Layout` does its work in methods that SwiftUI may call several times while it settles a screen: a parent can ask `sizeThatFits(proposal:subviews:cache:)` for a size under more than one proposal, and then `placeSubviews(in:proposal:subviews:cache:)` runs. A layout that measures every child in each call repeats the same work. The protocol therefore gives each layout **optional storage shared by its methods**; Apple's custom-layout sample calls it "a bidirectional `cache` parameter" that provides "optional storage that's shared among all the methods of a particular layout instance." Picture a flow layout of forty filter chips. Without a cache it asks every chip's proxy for its ideal size inside `sizeThatFits`, again for each further proposal the parent tries, and once more inside `placeSubviews`. Those answers do not change between the calls unless the chips do, which is exactly the kind of work a cache can hold. ## How the cache is declared 1. **Pick a type.** The protocol declares `associatedtype Cache = Void`. Leaving it alone means `cache: inout ()` in every signature and no caching at all. 2. **Build it.** When you declare your own `Cache` type you must implement **`makeCache(subviews:)`**, because the protocol supplies a default only when `Cache` is `Void`. It receives the `Subviews` collection and returns the first value. 3. **Read and write it.** `sizeThatFits`, `placeSubviews`, `spacing(subviews:cache:)` and both `explicitAlignment` methods take `cache: inout Cache`, so any of them can read stored values or fill in more. 4. **Refresh it.** Apple's sample says: "If the subviews change, SwiftUI calls the layout's `updateCache(_:subviews:)` method. The default implementation of that method calls `makeCache(subviews:)` again, which recalculates the data." Override it only when you can update the existing value more cheaply than rebuilding it. ## What belongs in it The test is what each value depends on: | Value | Depends on | Cache it? | |---|---|---| | each child's ideal size from `sizeThatFits(.unspecified)` | the subviews | yes | | each child's `ViewSpacing` or `priority` | the subviews | yes | | custom values read through a `LayoutValueKey` | the subviews | yes | | the row breaks of a flow layout | the subviews and the proposed width | only keyed by the width | | final positions | the bounds | no, compute them in `placeSubviews` | The trap is the fourth row. `makeCache(subviews:)` never receives a proposal, so row breaks computed there have no width to break against, and rows saved after the first `sizeThatFits` call go stale when a parent proposes a second width. Store the per-subview sizes and redo the cheap line-breaking on each call, or keep a small dictionary from width to rows. ## Treat it as derived data - **It is not state.** The cache is a performance aid that SwiftUI can rebuild through `updateCache` whenever the subviews change. Anything the container must remember across interactions belongs in view state that you pass in as a layout parameter. - **Layout parameters live on the struct.** Values such as `spacing` or a radius arrive as properties of the layout; use them in each method, or include them in a key, rather than baking them into numbers built once. - **Design for rebuilds.** Apple documents the subview trigger and nothing more, so make the cache correct to rebuild at any moment and never the only copy of anything. ## Is it worth it? Apple's sample adds a cache to its equal-width vertical stack and then says plainly: "Most simple layouts, including the equal-width vertical stack, don't gain much efficiency from using a cache." It recommends profiling with Instruments to find out whether a layout actually benefits. A strong answer follows that order: - start without a cache, with one helper that both required methods call; - measure with Instruments on a realistic screen, such as a filter sheet with forty chips at a large text size; - add a cache of per-subview measurements only when the measuring shows up, and keep proposal-dependent results out of it or keyed by the proposal. An interviewer who asks about the cache is usually checking two things: that you know the default `updateCache` simply rebuilds, and that you do not cache an answer that depends on the width.

  • Why must you implement makeCache once you declare your own Cache type?
    The protocol's default `makeCache(subviews:)` lives in an extension constrained to `Cache == ()`. With your own `Cache` type there is no default to fall back on, so the conformance needs `makeCache` to produce the first value. `updateCache(_:subviews:)` keeps its default, which calls your `makeCache` again.
  • When would you override updateCache instead of keeping the default?
    Only when you can patch the existing value more cheaply than rebuilding it. The default throws the old cache away by calling `makeCache` again; an override receives the old value `inout` together with the new subviews and can reuse what still applies. Most layouts never need this, which is why the default exists.

  • makeCache receives the proposal, so final row breaks can be cached there.
  • Every custom Layout should declare a cache for performance.
  • The default updateCache does nothing, so values stay stale unless you override it.
  • The layout cache is a good place to keep state across user interactions.
  • Declaring a custom Cache type still uses the default makeCache.