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

SOLVED: ViewModifier properties (let or var?)

Forums > SwiftUI

Hi!,

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 {
        content
            .offset(y: offsetAmount)
            .animation(.spring(response: 0.8, dampingFraction: 0.7, blendDuration: 0).delay(offsetDelay), value: offsetAmount)
            .opacity(opacityAmount)
            .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.

Thanks!

2      

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.

2      

Thank you so much!

2      

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.

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.