Reference: Demystify SwiftUI WWDC21
When SwiftUI looks at your code, it will look for three things:
- Identity
- Lifetime
- Dependencies
Identity
Explicit Identity: In this case, .dogTagID
represents the ID of the rescueDog
data type which conforms to the Identifiable
protocol.
- With a stable ID, SwiftUI can optimize performance.
Implicit or Structural Identity: If a statement or switch statement in a SwiftUI view’s body (@ViewBuilder) creates an implicit ID based on structural differences (i.e., the position of the view relative to its hierarchy).
- Avoid using AnyView if possible.
View Lifetime
- State Lifetime == View Lifetime, meaning when the view’s identity changes, the state is destroyed along with that identity.
With this implementation, when date < .now
, a different view modifier identity is created, which is not stable.
A better version would be to tie the condition in the value of opacity, so there is just a single View Modifier, which means better performance, more correct code, and SwiftUI is optimized for this kind of code.