TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: ViewModifier properties (let or var?)

Forums > SwiftUI


I have this ViewModifier in order to group 4 modifiers in just one in order to use with more than one View:

struct FadeInWithOffsetAnimation: ViewModifier {
    let opacityAmount: Double
    let opacityDelay: Double
    let offsetAmount: Double
    let offsetDelay: Double

    func body(content: Content) -> some View {
            .offset(y: offsetAmount)
            .animation(.spring(response: 0.8, dampingFraction: 0.7, blendDuration: 0).delay(offsetDelay), value: offsetAmount)
            .animation(.default.delay(opacityDelay), value: opacityAmount)

extension View {
    func fadeInWithOffsetAnimation(opacityAmount: Double, opacityDelay: Double, offsetAmount: Double, offsetDelay: Double) -> some View {
        modifier(FadeInWithOffsetAnimation(opacityAmount: opacityAmount, opacityDelay: opacityDelay, offsetAmount: offsetAmount, offsetDelay: offsetDelay))

I use it by this way:

@State private var opacityAnimationAmount = 0.0
@State private var offsetAnimationAmount = 20.0

VStack {
  VStack {
  .fadeInWithOffsetAnimation(opacityAmount: opacityAnimationAmount, opacityDelay: 0.2, offsetAmount: offsetAnimationAmount, offsetDelay: 0.3)
.onAppear {
            opacityAnimationAmount = 1.0
            offsetAnimationAmount = 0.0

How should the struct properties be declared? I have seen code both ways. I know that whenever possible we should use let over var but I don't know if in this scenario it would be correct. Either way the code works as expected.



Use let. There is no need for var since you won't be changing the values of the modifier. If the values you pass in (opacityAnimationAmount, etc.) change, the entire View will be rerendered, including the modifier with its new values.


Thank you so much!


Utilize "let" instead of "var" since the values of the modifier won't change. When you pass in new values (opacityAnimationAmount, etc.), the entire View will be rerendered, including the modifier with its updated values.


Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.