How to fix the issue in the code shown at 21:40

At 21:40 in the video the following code is shown:

(sorry for the screenshot but this talk doesn't have code copy enabled)

Luca points out this results in new view and storage every time dayTime changes. Say you wanted to fix it so it doesn't create a new view and storage every time, how would you do that?

Like this maybe?

var body: some View {
  let cr = CatRecorder()
  if dayTime {
      return cr.nightTimeStyle()
  }
  else {
      return cr
  }
}

But this code doesn't look very declarative. I've seen many struggle with applying modifiers conditionally (especially .hidden()) so thought I'd ask.

Replies

You'll need to use an inert view modifier.

Something along the lines of:

var body: some View {
  CatRecorder()
    .carStyle(dayTime ? .nightTime : .noStyle)
}

This way SwiftUI knows that this is the same view where the style might change.

With this declaration, the view identity is preserved, but its value (in this case the style value) might change over time