tezvyn:

Implicit .animation() vs explicit withAnimation

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

How SwiftUI ties animation to state changes.

OUTLINE

.animation(value:) animates a view when a tracked value changes; withAnimation wraps the state mutation so all dependent views animate.

WHAT THIS TESTS This checks whether you understand that SwiftUI animates state transitions, and the two ways to declare which transitions animate: attached to a view, or attached to the mutation.

A GOOD ANSWER COVERS The implicit modifier .animation(_:value:) is placed on a view and watches a specific value. When that value changes, SwiftUI animates the affected properties of that view and its subtree with the given animation. It is local and declarative. The explicit form, withAnimation(_:) { }, wraps the code that mutates state. Any view whose body depends on the state changed inside the closure animates using that animation. It is imperative at the call site and coordinates multiple views at once.

COMMON WRONG ANSWERS Mentioning the old .animation(_) modifier without a value, which is deprecated because it animated based on any change and caused surprising behavior. Saying withAnimation only affects the view it is written in; it actually affects all views observing that state. Claiming you cannot combine them.

LIKELY FOLLOW-UPS What happens if both are present: an explicit withAnimation can override or compose with an implicit one. How to disable animation for a particular change: wrap it in withAnimation(nil) or withTransaction. What Animatable and animatableData have to do with custom curves.

ONE CONCRETE EXAMPLE Implicit: a heart icon that scales when liked. You write Image(systemName:).scaleEffect(isLiked ? 1.3 : 1).animation(.spring(), value: isLiked). Toggling isLiked animates just that icon. Explicit: tapping a button should slide in a detail panel and fade a background dim view together. You write withAnimation(.easeInOut) { showDetail = true }, and both the panel offset and the overlay opacity, which read showDetail, animate in sync. The explicit form ties the coordinated transition to the single user action.

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.