Use when implementing SwiftUI animations, understanding VectorArithmetic, using @Animatable macro, choosing between spring and timing curve animations, or debugging animation behavior - comprehensive animation reference from iOS 13 through iOS 26
Inherits all available tools
Additional assets for this skill
This skill inherits all available tools. When active, it can use any tool Claude has access to.
Comprehensive guide to SwiftUI's animation system, from foundational concepts to advanced techniques. This skill covers the Animatable protocol, the iOS 26 @Animatable macro, animation types, and the Transaction system.
Core principle Animation in SwiftUI is mathematical interpolation over time, powered by the VectorArithmetic protocol. Understanding this foundation unlocks the full power of SwiftUI's declarative animation system.
Animation is the process of generating intermediate values between a start and end state.
.opacity(0) → .opacity(1)
While this animation runs, SwiftUI computes intermediate values:
0.0 → 0.02 → 0.05 → 0.1 → 0.25 → 0.4 → 0.6 → 0.8 → 1.0
How values are distributed
SwiftUI requires animated data to conform to VectorArithmetic, which provides:
protocol VectorArithmetic {
// Compute difference between two values
static func - (lhs: Self, rhs: Self) -> Self
// Scale values
static func * (lhs: Self, rhs: Double) -> Self
// Add values
static func + (lhs: Self, rhs: Self) -> Self
// Zero value
static var zero: Self { get }
}
Built-in conforming types
CGFloat, Double, Float, AngleCGPoint, CGSizeCGRectKey insight Vector arithmetic abstracts over the dimensionality of animated data. SwiftUI can animate all these types with a single generic implementation.
Int does not conform to VectorArithmetic because:
struct CounterView: View {
@State private var count: Int = 0
var body: some View {
Text("\(count)")
.animation(.spring, value: count)
}
}
Result: SwiftUI simply replaces the old text with the new one. No interpolation occurs.
struct AnimatedCounterView: View {
@State private var count: Float = 0
var body: some View {
Text("\(Int(count))")
.animation(.spring, value: count)
}
}
Result: SwiftUI interpolates 0.0 → ... → 100.0, and you display the rounded integer at each frame.
Animatable attributes conceptually have two values:
Example
.scaleEffect(selected ? 1.5 : 1.0)
When selected becomes true:
1.51.0 → 1.1 → 1.2 → 1.3 → 1.4 → 1.5 over timeThe Animatable protocol allows views to animate their properties by defining which data should be interpolated.
protocol Animatable {
associatedtype AnimatableData: VectorArithmetic
var animatableData: AnimatableData { get set }
}
SwiftUI builds an animatable attribute for any view conforming to this protocol.
Many SwiftUI modifiers conform to Animatable:
.scaleEffect() — Animates scale transform.rotationEffect() — Animates rotation.offset() — Animates position offset.opacity() — Animates transparency.blur() — Animates blur radius.shadow() — Animates shadow propertiesCircle, Rectangle, RoundedRectangleCapsule, Ellipse, PathShape implementationsWhen animating multiple properties, use AnimatablePair to combine vectors.
struct ScaleEffectModifier: ViewModifier, Animatable {
var scale: CGSize
var anchor: UnitPoint
// Combine two 2D vectors into one 4D vector
var animatableData: AnimatablePair<CGSize.AnimatableData, UnitPoint.AnimatableData> {
get {
AnimatablePair(scale.animatableData, anchor.animatableData)
}
set {
scale.animatableData = newValue.first
anchor.animatableData = newValue.second
}
}
func body(content: Content) -> some View {
content.scaleEffect(scale, anchor: anchor)
}
}
How it works
CGSize is 2-dimensional (width, height)UnitPoint is 2-dimensional (x, y)AnimatablePair fuses them into a 4-dimensional vectorstruct AnimatableNumberView: View, Animatable {
var number: Double
var animatableData: Double {
get { number }
set { number = newValue }
}
var body: some View {
Text("\(Int(number))")
.font(.largeTitle)
}
}
// Usage
AnimatableNumberView(number: value)
.animation(.spring, value: value)
How it works
number changes from 0 to 100body for every frame of the animationnumber value: 0 → 5 → 15 → 30 → 55 → 80 → 100Custom Animatable conformance can be expensive.
When you conform a view to Animatable:
body for every frame of the animationBuilt-in animatable effects (like .scaleEffect(), .opacity()) are much more efficient:
Guideline
// This is expensive but necessary for animating along a circular path
@Animatable
struct RadialLayout: Layout {
var offsetAngle: Angle
var animatableData: Angle.AnimatableData {
get { offsetAngle.animatableData }
set { offsetAngle.animatableData = newValue }
}
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
proposal.replacingUnspecifiedDimensions()
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let radius = min(bounds.width, bounds.height) / 2
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let angleStep = Angle.degrees(360.0 / Double(subviews.count))
for (index, subview) in subviews.enumerated() {
let angle = offsetAngle + angleStep * Double(index)
let x = center.x + radius * cos(angle.radians)
let y = center.y + radius * sin(angle.radians)
subview.place(at: CGPoint(x: x, y: y), anchor: .center, proposal: .unspecified)
}
}
}
Why necessary: Animating offsetAngle requires recalculating positions every frame. No built-in modifier can do this.
The @Animatable macro eliminates the boilerplate of manually conforming to the Animatable protocol.
Before iOS 26, you had to:
AnimatableanimatableData getter and setterAnimatablePair for multiple propertiesiOS 26+, you just add @Animatable:
@MainActor
@Animatable
struct MyView: View {
var scale: CGFloat
var opacity: Double
var body: some View {
// ...
}
}
The macro automatically:
Animatable conformanceanimatableData from VectorArithmetic-conforming propertiesAnimatablePairstruct HikingRouteShape: Shape {
var startPoint: CGPoint
var endPoint: CGPoint
var elevation: Double
var drawingDirection: Bool // Don't want to animate this
// Tedious manual animatableData declaration
var animatableData: AnimatablePair<AnimatablePair<CGFloat, CGFloat>,
AnimatablePair<Double, AnimatablePair<CGFloat, CGFloat>>> {
get {
AnimatablePair(
AnimatablePair(startPoint.x, startPoint.y),
AnimatablePair(elevation, AnimatablePair(endPoint.x, endPoint.y))
)
}
set {
startPoint = CGPoint(x: newValue.first.first, y: newValue.first.second)
elevation = newValue.second.first
endPoint = CGPoint(x: newValue.second.second.first, y: newValue.second.second.second)
}
}
func path(in rect: CGRect) -> Path {
// Drawing code
}
}
@Animatable
struct HikingRouteShape: Shape {
var startPoint: CGPoint
var endPoint: CGPoint
var elevation: Double
@AnimatableIgnored
var drawingDirection: Bool // Excluded from animation
func path(in rect: CGRect) -> Path {
// Drawing code
}
}
Lines of code: 20 → 12 (40% reduction)
Use @AnimatableIgnored to exclude properties from animation.
@MainActor
@Animatable
struct ProgressView: View {
var progress: Double // Animated
var totalItems: Int // Animated (if Float, not if Int)
@AnimatableIgnored
var title: String // Not animated
@AnimatableIgnored
var startTime: Date // Not animated
@AnimatableIgnored
var debugEnabled: Bool // Not animated
var body: some View {
VStack {
Text(title)
ProgressBar(value: progress)
if debugEnabled {
Text("Started: \(startTime.formatted())")
}
}
}
}
Numeric animations are extremely common across app categories:
@MainActor
@Animatable
struct StockPriceView: View {
var price: Double
var changePercent: Double
var body: some View {
VStack(alignment: .trailing) {
Text("$\(price, format: .number.precision(.fractionLength(2)))")
.font(.title)
Text("\(changePercent > 0 ? "+" : "")\(changePercent, format: .percent)")
.foregroundColor(changePercent > 0 ? .green : .red)
}
}
}
Use case: Animate stock price changes, portfolio value, account balance transitions
@MainActor
@Animatable
struct HeartRateView: View {
var bpm: Double
@AnimatableIgnored
var timestamp: Date
var body: some View {
VStack {
Text("\(Int(bpm))")
.font(.system(size: 60, weight: .bold))
Text("BPM")
.font(.caption)
.foregroundColor(.secondary)
}
}
}
Use case: Heart rate indicators, step counters, calorie calculations, distance traveled
@MainActor
@Animatable
struct ScoreView: View {
var score: Float
var multiplier: Float
var body: some View {
HStack {
Text("\(Int(score))")
.font(.largeTitle)
Text("×\(multiplier, format: .number.precision(.fractionLength(1)))")
.font(.title2)
.foregroundColor(.orange)
}
}
}
Use case: Score animations, XP transitions, level progress, combo multipliers
@MainActor
@Animatable
struct TimerView: View {
var remainingSeconds: Double
var body: some View {
let minutes = Int(remainingSeconds) / 60
let seconds = Int(remainingSeconds) % 60
Text(String(format: "%02d:%02d", minutes, seconds))
.font(.system(.largeTitle, design: .monospaced))
}
}
Use case: Progress bars, countdown timers, percentage indicators, task completion metrics
struct ContentView: View {
@State private var stockPrice: Double = 142.50
var body: some View {
VStack(spacing: 20) {
StockPriceView(price: stockPrice, changePercent: 0.025)
.animation(.spring(duration: 0.8), value: stockPrice)
Button("Simulate Price Change") {
stockPrice = Double.random(in: 130...160)
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}
@MainActor
@Animatable
struct StockPriceView: View {
var price: Double
var changePercent: Double
var body: some View {
VStack(alignment: .trailing) {
Text("$\(price, format: .number.precision(.fractionLength(2)))")
.font(.title)
.fontWeight(.semibold)
Text("\(changePercent > 0 ? "+" : "")\(changePercent, format: .percent.precision(.fractionLength(2)))")
.font(.subheadline)
.foregroundColor(changePercent > 0 ? .green : .red)
}
}
}
Result: Smooth, natural animation of stock price changes that feels professional and polished.
Timing curve animations use bezier curves to control the speed of animation over time.
.animation(.linear) // Constant speed
.animation(.easeIn) // Starts slow, ends fast
.animation(.easeOut) // Starts fast, ends slow
.animation(.easeInOut) // Slow start and end, fast middle
let customCurve = UnitCurve(
startControlPoint: CGPoint(x: 0.2, y: 0),
endControlPoint: CGPoint(x: 0.8, y: 1)
)
.animation(.timingCurve(customCurve, duration: 0.5))
All timing curve animations accept an optional duration:
.animation(.easeInOut(duration: 0.3))
.animation(.linear(duration: 1.0))
Default: 0.35 seconds
Spring animations use physics simulation to create natural, organic motion.
.animation(.smooth) // No bounce (default since iOS 17)
.animation(.snappy) // Small amount of bounce
.animation(.bouncy) // Larger amount of bounce
.animation(.spring(duration: 0.6, bounce: 0.3))
Parameters
duration — Perceived animation durationbounce — Amount of bounce (0 = no bounce, 1 = very bouncy)Much more intuitive than traditional spring parameters (mass, stiffness, damping).
Modify base animations to create complex effects.
.animation(.spring.delay(0.5))
Waits 0.5 seconds before starting the animation.
.animation(.easeInOut.repeatCount(3, autoreverses: true))
.animation(.linear.repeatForever(autoreverses: false))
Repeats the animation multiple times or infinitely.
.animation(.spring.speed(2.0)) // 2x faster
.animation(.spring.speed(0.5)) // 2x slower
Multiplies the animation speed.
Before iOS 17
withAnimation {
// Used timing curve by default
}
iOS 17+
withAnimation {
// Uses .smooth spring by default
}
Why the change: Spring animations feel more natural and preserve velocity when interrupted.
Recommendation: Embrace springs. They make your UI feel more responsive and polished.
The most common way to trigger an animation.
Button("Scale Up") {
withAnimation(.spring) {
scale = 1.5
}
}
How it works
withAnimation opens a transactionwithAnimation(.spring(duration: 0.6, bounce: 0.4)) {
isExpanded.toggle()
}
withAnimation(nil) {
// Changes happen immediately, no animation
resetState()
}
Apply animations to specific values within a view.
Circle()
.fill(isActive ? .blue : .gray)
.animation(.spring, value: isActive)
How it works: Animation only applies when isActive changes. Other state changes won't trigger this animation.
Circle()
.scaleEffect(scale)
.animation(.bouncy, value: scale)
.opacity(opacity)
.animation(.easeInOut, value: opacity)
Different animations for different properties.
Narrowly scope animations to specific animatable attributes.
struct AvatarView: View {
var selected: Bool
var body: some View {
Image("avatar")
.scaleEffect(selected ? 1.5 : 1.0)
.animation(.spring, value: selected)
// ⚠️ If image also changes when selected changes,
// image transition gets animated too (accidental)
}
}
struct AvatarView: View {
var selected: Bool
var body: some View {
Image("avatar")
.animation(.spring, value: selected) {
$0.scaleEffect(selected ? 1.5 : 1.0)
}
// ✅ Only scaleEffect animates, image transition doesn't
}
}
How it works
Define your own transaction values to propagate custom context.
struct AvatarTappedKey: TransactionKey {
static let defaultValue: Bool = false
}
extension Transaction {
var avatarTapped: Bool {
get { self[AvatarTappedKey.self] }
set { self[AvatarTappedKey.self] = newValue }
}
}
var transaction = Transaction()
transaction.avatarTapped = true
withTransaction(transaction) {
isSelected.toggle()
}
.transaction { transaction in
if transaction.avatarTapped {
transaction.animation = .bouncy
} else {
transaction.animation = .smooth
}
}
Use case: Apply different animations based on how the state change was triggered (tap vs programmatic).
Implement your own animation algorithms.
protocol CustomAnimation {
// Calculate current value
func animate<V: VectorArithmetic>(
value: V,
time: TimeInterval,
context: inout AnimationContext<V>
) -> V?
// Optional: Should this animation merge with previous?
func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool
// Optional: Current velocity
func velocity<V: VectorArithmetic>(
value: V,
time: TimeInterval,
context: AnimationContext<V>
) -> V?
}
struct LinearAnimation: CustomAnimation {
let duration: TimeInterval
func animate<V: VectorArithmetic>(
value: V, // Delta vector: target - current
time: TimeInterval, // Elapsed time since animation started
context: inout AnimationContext<V>
) -> V? {
// Animation is done when time exceeds duration
if time >= duration {
return nil
}
// Calculate linear progress (0.0 to 1.0)
let progress = time / duration
// Scale the delta vector by progress
// This returns how much to move FROM current position
// NOT the final target position
return value.scaled(by: progress)
}
}
Critical understanding: The value parameter is the delta vector (target - current), not the target value itself.
Example in practice:
10.0100.0animate(): 90.0 (target - current)return value.scaled(by: 0.5) → returns 45.010.0 + 45.0 = 55.0 (halfway to target) ✅Common mistake:
// ❌ WRONG: Treating value as the target
let progress = time / duration
return value.scaled(by: progress) // This assumes value is delta
// ❌ WRONG: Trying to interpolate manually
let target = value // No! value is already the delta
return current + (target - current) * progress // Incorrect
// ✅ CORRECT: Scale the delta
return value.scaled(by: progress) // SwiftUI handles the addition
What happens when a new animation starts before the previous one finishes?
func shouldMerge(...) -> Bool {
return false // Default implementation
}
Behavior: Both animations run together, results are combined additively.
Example
func shouldMerge(...) -> Bool {
return true // Springs override this
}
Behavior: New animation incorporates state of previous animation, preserving velocity.
Example
Why springs feel more natural: They preserve momentum when interrupted.
Built-in animatable attributes run efficiently:
.scaleEffect(scale)
.opacity(opacity)
.rotationEffect(angle)
Benefits
bodyCustom Animatable conformance runs on main thread:
@MainActor
@Animatable
struct MyView: View {
var value: Double
var animatableData: Double {
get { value }
set { value = newValue }
}
var body: some View {
// Called every frame! (main thread)
}
}
Performance tip: Profile with Instruments if you have many custom animatable views.
SwiftUI animates the difference between values, not the values themselves.
// User taps, scale changes from 1.0 to 1.5
.scaleEffect(isSelected ? 1.5 : 1.0)
What SwiftUI actually animates
Why this matters
Symptom: Property changes but doesn't animate.
@State private var count: Int = 0 // ❌ Int doesn't animate
// Solution
@State private var count: Double = 0 // ✅ Double animates
Text("\(Int(count))") // Display as Int
// ❌ No animation specified
Text("\(value)")
// ✅ Add animation
Text("\(value)")
.animation(.spring, value: value)
struct ProgressView: View {
@State private var progress: Double = 0
@State private var title: String = "Loading"
var body: some View {
VStack {
Text(title)
ProgressBar(value: progress)
}
.animation(.spring, value: title) // ❌ Animates when title changes, not progress
}
}
// Solution
.animation(.spring, value: progress) // ✅
If you have a custom view with animatable properties:
// ❌ Missing Animatable conformance
struct MyView: View {
var value: Double
var body: some View { ... }
}
// ✅ Add @Animatable macro (iOS 26+)
@MainActor
@Animatable
struct MyView: View {
var value: Double
var body: some View { ... }
}
// ✅ OR manual conformance (iOS 13+)
struct MyView: View, Animatable {
var value: Double
var animatableData: Double {
get { value }
set { value = newValue }
}
var body: some View { ... }
}
Symptom: Animation is choppy or drops frames.
@MainActor
@Animatable
struct ExpensiveView: View {
var value: Double
var animatableData: Double {
get { value }
set { value = newValue }
}
var body: some View {
// ❌ Called every frame!
let heavyComputation = performExpensiveWork(value)
return Text("\(heavyComputation)")
}
}
Solution: Use built-in effects instead
struct OptimizedView: View {
@State private var value: Double = 0
var body: some View {
Text("\(computeOnce(value))")
.opacity(value) // ✅ Built-in effect, off-main-thread
}
}
Profile with Instruments to identify bottlenecks.
Symptom: Animation behavior changes when interrupted.
Cause: Spring animations merge by default, preserving velocity from the previous animation.
Solution: Use a timing curve animation if you don't want merging behavior:
// ❌ Spring merges with previous animation
withAnimation(.spring) {
scale = 1.0
}
// ✅ Timing curve starts fresh (additive, no merge)
withAnimation(.easeInOut(duration: 0.5)) {
scale = 1.0
}
See Animation Merging Behavior section above for detailed explanation of merge vs additive animations.
Last Updated Based on WWDC 2023/10156, WWDC 2025/256, and iOS 26 Beta Version iOS 13+ (Animatable protocol), iOS 17+ (scoped animations), iOS 26+ (@Animatable macro)