Are there negative impacts to using constants in SwiftUI View structs?

Viewed 79

A coworker is claiming that we should not use constants in SwiftUI View structs. Even for properties of a value type where the value will not change.

For example, they say this is not good:

struct FlagView: View {
    let flagIcon = Image(systemName: "flag")
    var body: some View {
        VStack {
            flagIcon
            Text("Flags")
            flagIcon
        }
    }
}

But do this instead:

struct FlagView: View {
    var flagIcon: Image { Image(systemName: "flag") }
    var body: some View {
        VStack {
            flagIcon
            Text("Flags")
            flagIcon
        }
    }
}

Their explanation sounds like cargo cult based on their misinterpretation of Apple tutorial code and ignorance of fundamentals. However, proving that is elusive. Apple documentation is not going to explain every crazy thing we should not do because that is an infinite list.

Or maybe there is magic in SwiftUI I am ignorant of.

Is their assertion correct? If yes or no, please explain why.

Note, I realize this is a simplistic example and really we would type the Image out twice in the VStack. I am trying to focus on the general case.

1 Answers

In their typical fashion, Apple have frustratingly hidden vital info in WWDC videos. After scouring them all day, I have found to my surprise that Apple has addressed this exact topic at least twice. My coworker's misapprehension must be common because Apple felt the need to clarify.

  1. WWDC20 Introduction to SwiftUI
  2. WWDC20 Data Essentials in SwiftUI

From Introduction to SwiftUI:

And technically, any constant can serve as a perfectly good read-only source of truth. The test data driving our previews is an example of this.

4 squares showing sources of truth types

From Data Essentials in SwiftUI

And how will the view manipulate this data? It just displays the data, it doesn't change it, so these can be "let" properties.

View source code highlighting let

Your data's lifetime is important, but that lifetime is tied to the lifetime of its source of truth, and in all of the previous examples, we've used tools like State, StateObject, and Constants.

3 buttons showing types of source of truth

Related