Contents

speed(_:)

Changes the duration of an animation by adjusting its speed.

Declaration

func speed(_ speed: Double) -> Animation

Parameters

  • speed:

    The speed at which SwiftUI performs the animation.

Return Value

An animation with the adjusted speed.

Discussion

Setting the speed of an animation changes the duration of the animation by a factor of speed. A higher speed value causes a faster animation sequence due to a shorter duration. For example, a one-second animation with a speed of 2.0 completes in half the time (half a second).

struct ContentView: View {
    @State private var adjustBy = 100.0

    private var oneSecondAnimation: Animation {
       .easeInOut(duration: 1.0)
    }

    var body: some View {
        VStack(spacing: 40) {
            HStack(alignment: .bottom) {
                Capsule()
                    .frame(width: 50, height: 175 - adjustBy)
                Capsule()
                    .frame(width: 50, height: 175 + adjustBy)
            }
            .animation(oneSecondAnimation.speed(2.0), value: adjustBy)

            Button("Animate") {
                adjustBy *= -1
            }
        }
    }
}

Setting speed to a lower number slows the animation, extending its duration. For example, a one-second animation with a speed of 0.25 takes four seconds to complete.

struct ContentView: View {
    @State private var adjustBy = 100.0

    private var oneSecondAnimation: Animation {
       .easeInOut(duration: 1.0)
    }

    var body: some View {
        VStack(spacing: 40) {
            HStack(alignment: .bottom) {
                Capsule()
                    .frame(width: 50, height: 175 - adjustBy)
                Capsule()
                    .frame(width: 50, height: 175 + adjustBy)
            }
            .animation(oneSecondAnimation.speed(0.25), value: adjustBy)

            Button("Animate") {
                adjustBy *= -1
            }
        }
    }
}

See Also

Configuring an animation