tezvyn:

The Animatable Protocol

AI-drafted, machine-checkedSource: developer.apple.comadvanced
The Animatable Protocol

The Animatable protocol lets a custom SwiftUI view or Shape expose its state as interpolatable data, so SwiftUI can smoothly tween between values across frames instead of snapping, which is how custom shapes and progress indicators get real animation.

WHY IT EXISTS SwiftUI is a declarative framework: you describe what the UI looks like for a given state, and SwiftUI figures out how to render it, including how to animate between two states. That only works if SwiftUI has a generic way to compute what the state halfway between old and new looks like for arbitrary custom types, not just the built-in modifiers like offset or opacity. The Animatable protocol exists to give any custom view or Shape that same interpolation contract.

THE MENTAL MODEL Think of Animatable as handing SwiftUI a single knob instead of a finished picture. You do not tell SwiftUI how to draw each intermediate animation frame yourself, you just expose your view's state as one numeric value, or a pair of them, that supports addition, subtraction, and scaling. SwiftUI turns that knob smoothly from the old value to the new one, calling your view's body once per frame with whatever intermediate value the knob currently reads.

HOW IT WORKS A conforming type implements animatableData as a computed property of some type conforming to VectorArithmetic, which itself builds on AdditiveArithmetic. When a state change triggers an animation, SwiftUI computes an interpolated animatableData value for each frame between the old and new value, sets that value on your view, and re-renders. If your shape needs more than one animatable number, AnimatablePair bundles two animatableData values, or nests further for more. Common numeric types like Double and CGFloat already conform out of the box, and Shape already refines Animatable, which is why custom shapes are the most common place to implement it.

WHEN IT MATTERS It matters whenever you build a custom Shape or view modifier that needs to morph smoothly, a progress ring, a custom polygon, a wave. The footgun is forgetting the conformance entirely: only the property mapped to animatableData gets interpolated, so any other stored property changes just snap instantly on the next frame, silently breaking an animation that looks fine in isolation but jumps the moment two properties change together.

ONE CONCRETE EXAMPLE A custom circular progress ring Shape stores a progress value of type Double. Conforming to Animatable and mapping animatableData to progress lets an animation modifier tied to that value sweep the ring smoothly from 40 percent to 75 percent over its duration, instead of the ring jumping instantly from one arc length to the other.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.