Core Engine
AttributeGraph — SwiftUI's real engine, not a virtual DOM
SwiftUI is not Apple's React. While both use declarative descriptions, SwiftUI's engine is architecturally closer to MobX or Vue's fine-grained reactivity than to React's virtual DOM. The private C++ library AttributeGraph (AG) maintains a directed acyclic graph of attribute nodes — and it's what actually runs the show, with SwiftUI being a thin veneer on top for platform-appropriate controls and a stable interface.
Each node represents an input (a @State value, an environment setting) or a rule (a computed value like a view's body). Dependencies are captured implicitly at access time — when SwiftUI evaluates body, any state property that is read registers a dependency edge. If you never read a property in body, no edge is created and changes won't trigger re-evaluation.
- depends on
- push: dirty
- pull: re-evaluated
Click @State or @Environment to trigger an update
The graph is based on a 1996 paper by Scott Hudson: "A System for Efficient and Flexible One-Way Constraint Evaluation in C++". It's divided into subgraphs that correspond to logical UI units — when a conditional branch disappears, its entire subgraph is torn down, similar to React unmounting a subtree.
Changes are batched into transactions, analogous to React 18's automatic batching. Multiple state changes within the same transaction produce a single re-evaluation pass.
View Lifecycle
View identity — what SwiftUI preserves and what it destroys
SwiftUI identifies views through two mechanisms, directly analogous to React's reconciliation rules.
Structural identity is the default: views are identified by their type and position in the hierarchy. A VStack { A(); B(); C() } identifies children by index — exactly like React matching children by position. An if/else compiles to _ConditionalContent<TrueView, FalseView> where both branches have different identities. Switching branches destroys state and triggers transitions.
// These are TWO different views to SwiftUI:
if showDetail {
DetailView() // _ConditionalContent.TrueContent
} else {
SummaryView() // _ConditionalContent.FalseContent
}
// Switching destroys state!
// To PRESERVE state, use inert modifiers:
DetailView()
.opacity(showDetail ? 1 : 0)Explicit identity works like React's key prop. The .id(someHashableValue) modifier assigns a stable identifier — changing it forces SwiftUI to treat the view as entirely new.ForEach requires Identifiable data for the same reason React needs keys in lists.
Unlike React components which are JavaScript functions that execute top-down, SwiftUI views are value-type structs. The struct itself is ephemeral — it gets recreated on each parent re-evaluation. But @State storage persists because AG maintains it externally, keyed to the view's identity. The struct is a description, not the view itself.
Rendering
From SwiftUI views to pixels — the full six-stage pipeline
The journey from a SwiftUI view description to photons hitting your retina crosses six distinct boundaries. Understanding this pipeline is essential for performance work.
Stage 1–2: View evaluation → AttributeGraph. SwiftUI's ViewGraph maintains two hierarchies. The ViewList is the structural definition from body evaluations — ephemeral, value-typed, discarded after processing. The DisplayList is the rendering hierarchy — a scene graph of items with identity, version, frame rects, effects, shapes, and paints.
(item
#:identity 1
#:version 13
(frame (185.67 417.67; 21.67 21.67))
(shape (path ...) (paint ...)))Stage 3: Mapping to CALayers. The critical insight: SwiftUI does NOT create one CALayer per view. The layer tree is aggressively flattened. Layout containers (VStack, HStack, Spacer) produce no UIView or CALayer — they exist only during layout computation. Graphics primitives become _UIGraphicsView, text becomes CGDrawingView, and UIKit-wrapped controls use actual UIKit views.
Stage 4–5: CoreAnimation commit → Render server. This is architecturally analogous to Chromium's compositor commit. CoreAnimation maintains three parallel layer trees:
- Model TreeProperties as set by app code
- Presentation TreeIn-flight animated values
- Render TreeServer-side copy in backboardd
At each run loop iteration's end, an implicit CATransaction commits the layer tree diff via Mach IPC to an out-of-process render server: backboardd on iOS,WindowServer on macOS. This process runs outside your app sandbox with GPU access.
Stage 6: GPU execution. All iOS GPUs use Tile-Based Deferred Rendering (TBDR). Geometry is binned into screen-space tiles sized to fit the SoC cache. Each tile is processed independently with automatic hidden surface removal. Each offscreen pass (blur, mask) costs ~0.1–0.2ms. A blur ≈ 5 render passes. For 60fps you have 16.67ms total, and the pipeline spans ~3 frames via pipelining. ProMotion's 120fps halves the budget to 8.33ms.
Layout System
SwiftUI's layout inverts CSS's authority hierarchy
In CSS, the parent has final authority — width: 100% stretches a child to fill the parent, and Flexbox's flex-grow lets the parent dictate sizing. In SwiftUI, the child always gets final say.
The three-step negotiation: the parent proposes a size ("you have 375×812 pts"), the child chooses its own size (Text measures: "I need 120×20"), and the parent places the child in its coordinate space. The child cannot be stretched beyond what it accepts. Think of it as if every CSS element had width: fit-content by default with an intrinsic size that can't be overridden from outside.
| Concept | CSS/Web | SwiftUI |
|---|---|---|
| Horizontal layout | display: flex; flex-direction: row | HStack { ... } |
| Vertical layout | flex-direction: column | VStack { ... } |
| Stacking/overlap | position: relative + absolute | ZStack { ... } |
| Fill remaining space | flex-grow: 1 on empty div | Spacer() |
| Scroll | overflow: scroll (any element) | ScrollView { } (explicit wrapper) |
| Grid | display: grid (powerful) | LazyVGrid / LazyHGrid (limited) |
| Wrap/flow | flex-wrap: wrap | No built-in (need Layout protocol) |
| Authority | Parent controls sizing | Child chooses its own size |
| Custom layout engine | Not possible in CSS alone | Layout protocol (iOS 16+) |
struct RadialLayout: Layout {
func sizeThatFits(
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) -> CGSize {
// Return how much space we need
proposal.replacingUnspecifiedDimensions()
}
func placeSubviews(
in bounds: CGRect,
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) {
let radius = min(bounds.width, bounds.height) / 2
for (i, subview) in subviews.enumerated() {
let angle = 2 * .pi / CGFloat(subviews.count) * CGFloat(i)
let x = bounds.midX + radius * cos(angle)
let y = bounds.midY + radius * sin(angle)
subview.place(at: CGPoint(x: x, y: y), anchor: .center,
proposal: .unspecified)
}
}
}Motion
SwiftUI animations don't use CAAnimation
This surprises most people: SwiftUI animations do NOT use CAAnimation. Views conforming to Animatable expose animatableData, and SwiftUI interpolates these values each frame using the specified timing curve, generating new CALayer property values committed via the normal CATransaction pipeline.
This is fundamentally a main-thread animation model — like React Native's JS-driven animations — not a server-side model like CSS transitions that map to compositor animations. The compositing of updated properties still happens in the render server, but the interpolation math runs in your app process. This makes SwiftUI animations susceptible to main-thread jank.
- CSS TransitionCompositor-side interpolation. Main thread free during animation. Limited to compositor properties.
- SwiftUI AnimationMain-thread interpolation via Animatable protocol. New property values committed each frame via CATransaction.
- CAAnimationRender-server interpolation. Used by UIKit, NOT by SwiftUI. Runs independent of app process.
SwiftUI provides drawingGroup() to flatten a subtree into a single Metal texture — dramatically faster for complex overlapping graphics but loses per-element hit-testing. Canvas (iOS 15+) provides immediate-mode GPU drawing. iOS 17+ added .colorEffect(), .distortionEffect(), and .layerEffect() — stitchable Metal fragment shaders operating on layer textures.
React ↔ SwiftUI
Property wrappers vs hooks, and everything between
SwiftUI's @State, @Binding, @Observable, and @Environment are declarative annotations — the compiler wires up reactivity. React hooks are imperative calls that execute during render. The mapping is close but the mechanisms differ.
| Concept | React | SwiftUI |
|---|---|---|
| Internal tree | Fiber tree (virtual DOM) | AttributeGraph (dependency DAG) |
| Change detection | Tree-wide VDOM diffing | Targeted dependency tracking |
| Identity (default) | Position + element type | Position + Swift type (structural) |
| Identity (explicit) | key prop | .id() modifier / Identifiable |
| Local state | useState (hook) | @State (property wrapper) |
| Shared state | Context + useContext | @Environment / @Observable |
| Two-way binding | Not built-in (callbacks) | @Binding |
| Side effects | useEffect | .onAppear / .onChange / .task |
| Memoization | React.memo / useMemo | Built-in via AG (automatic) |
| Dependency tracking | None (re-renders subtree) | Automatic via getter interception |
| Update batching | Automatic (React 18+) | Transactions |
| Component type | JS function (reference type) | Swift struct (value type) |
@Observable (iOS 17+) provides property-level tracking — only views that read the specific changed property re-evaluate. This is far more granular than the older ObservableObject, which notified all observers on any @Published change. There's no equivalent in React — you'd need Jotai, Valtio, or MobX for this level of granularity.
Philosophy
"Learn once, apply everywhere" — not "write once, run everywhere"
Apple's philosophy is explicitly stated: same skills, same concepts, same APIs — but the UI adapts to each platform's conventions. A Toggle becomes a switch on iOS, a checkbox on macOS, and a toggle button on watchOS. A NavigationSplitView shows a multi-column layout on macOS, a sidebar on iPadOS, collapses to a stack on iPhone, and renders with glass material on visionOS.
- iOSUIKit hosting layer, UINavigationController under the hood
- macOSAppKit hosting, NSWindow management, menu bar integration
- iPadOSMulti-column navigation, keyboard/trackpad support
- watchOSDigital Crown, compact layouts, WKHostingController
- tvOSFocus engine, remote-driven navigation, large-screen layouts
- visionOSSwiftUI-only platform. Eye tracking, spatial layout, glass materials
What's truly shared: data models, business logic, state management (@State, @Observable), core views (Text, Image, Button, List, stacks), layout primitives, and animation APIs. What requires #if os() guards: navigation patterns, input methods, window management, and platform-specific controls.
visionOS is notable: SwiftUI is the only UI framework available — no UIKit or AppKit. This validates SwiftUI's completeness as a standalone rendering system. As of 2026, roughly 70% of new apps use SwiftUI, while ~80% of enterprise/legacy apps remain on UIKit. Most professional teams use a hybrid approach.
iOS / macOS 26
Liquid Glass — SDFs pushed into CoreAnimation's layer pipeline
Liquid Glass is Apple's most significant design overhaul since iOS 7, shipped across all platforms except visionOS at WWDC 2025 (the version jump from 18 → 26 aligns OS versions with calendar year + 1). Unlike previous blur-based materials that scatter light, Liquid Glass bends and concentrates light in real-time, simulating physical glass optics with refraction, specular highlights, chromatic aberration, and adaptive shadows.
- vibrantColorMatrixFinal toning CAFilterL6
- CASDFGlassHighlightEffectEdge lighting at 2 opposing anglesL5
- glassBackground CAFilterRefraction + blur + vibrancyL4
- CASDFLayer → SDF TextureSDF shape → GPU textureL3
- CASDFElementLayerDefines SDF geometry (superellipse)L2
- CABackdropLayerCaptures background contentL1
↑ composited bottom-to-top by render server
The rendering pipeline chains these layers: CABackdropLayer captures the background →CASDFLayer generates the SDF texture → glassBackground CAFilter applies refraction, blur, and vibrancy → CASDFGlassHighlightEffect adds edge highlights →vibrantColorMatrix CAFilter tones the final output.
How SDFs enable the "liquid" morphing
A Signed Distance Function returns the distance from any pixel to the shape boundary — negative inside, zero at the edge, positive outside. The screen-space gradient creates "fake" 3D surface normals from a 2D shape. These normals drive Snell's Law refraction to offset background texture sampling (index of refraction ~1.52), and Fresnel reflections intensify edge lighting at grazing angles.
The signature "liquid" behavior comes from SDF smooth boolean operations — theGlassEffectContainer API uses smooth union to merge nearby glass elements organically:
float smoothUnion(float d1, float d2, float smoothness) {
float h = max(smoothness - abs(d1 - d2), 0.0)
/ smoothness;
return min(d1, d2) - h * h * smoothness * 0.25;
}
// d1, d2 = SDF distances for two glass elements
// smoothness = merge radius (larger = gooier blend)
// Returns: merged SDF with organic transitionThis smooth union produces the "gooey" organic blending when glass elements approach each other — a technique pioneered by Íñigo Quílez in the shader art community, now deployed at the OS compositor level.
SwiftUI API for developers
// Basic glass effect
Text("Hello")
.glassEffect(.regular, in: .rect(cornerRadius: 12))
// Glass variants
.glassEffect(.clear) // High transparency
.glassEffect(.regular) // Default
.glassEffect(.identity) // Disabled (no glass)
// Tinting
.glassEffect(.regular, in: .capsule)
.tint(.blue)
// Grouped elements merge organically
GlassEffectContainer {
HStack(spacing: 12) {
Button("Play") { }
.glassEffect(.regular, in: .circle)
Button("Next") { }
.glassEffect(.regular, in: .circle)
}
}
// ↑ Buttons merge when close via smooth unionThree things to internalize
- 01Dependency tracking replaces tree diffingAttributeGraph's fine-grained reactivity is closer to Solid.js or MobX than to React's virtual DOM. React.memo-style optimization is unnecessary — it's the default.
- 02The child owns its sizeSwiftUI's layout negotiation inverts CSS's parent-driven authority. Fighting it with .frame() everywhere is like using !important in CSS — a sign you're working against the system.
- 03The compositor is a first-class citizenCoreAnimation's out-of-process render server gives compositor-level performance by default on ALL layer properties — not just the handful of compositor-friendly CSS properties.
Further reading: Saagar Jha — "Making Friends with AttributeGraph" · Rens Breur — "Untangling the AttributeGraph" · objc.io — Swift Talk AG episodes · ShatteredGlass — Liquid Glass deconstruction · Victor Baro — "SDF in Metal: Adding the Liquid to the Glass"