【SwiftUI】withAnimation() ↔ .animation()

特に、ざっくり

「あればいいかな」

くらいにアニメーションつけてました。


@State var animate1 = false

Text("😬")
  .font(.system(size: 200))
  .scaleEffect(animate1 ? 0.5 : 1.5)
  .rotationEffect(.degrees(animate1 ? 0 : 360))

  .onAppear {
    withAnimation(.default.repeatForever()) {
      animate1.toggle()
    }
  }

👉 withAnimation(_:_:) | Apple Developer Documentation hatena-bookmark

一方で、よく見かける似たような記述。


@State var animate2 = false

Text("😬")
  .font(.system(size: 200))
  .scaleEffect(animate2 ? 0.5 : 1.5)
  .rotationEffect(.degrees(animate2 ? 0 : 360))

  .animation(
    .default.repeatForever(),
    value: animate2
  )
  .onAppear {
    animate2.toggle()
  }

👉 animation(_:value:) | Apple Developer Documentation hatena-bookmark

どう違うのか並べてみましたが。

一緒ですね。

後者のほうが細かく使えそうな気がしますが、

前者のほうが簡潔です。