swiftuistructvarmutablelet

Non-state variable inside SwiftUI View


I just rewatched Demistify SwiftUI and noticed that some of the examples use variable properties inside a SwiftUI View, without using the @State property wrapper. For example (around 19.04):

struct PurrDecibelView: View {
    var intensity: Double

    var body: some View {
        // ...
    }

It does not seem to be possible to change this property from any action defined in its body. Is there any reason for choosing a var over let here?


Solution

  • I can't see a reason for for choosing var over let in the specific case you have shared, but there could be some reasons like:

    1. Default value and default initializer

    If you set a default value to a let variable, it will not be present in the default initializer of the struct. But making it var will cause it to be an optional parameter: Var Demo

    2. Outside the body

    Since View is just a protocol you conform to, there may be some reasons to have functionalities outside the body that you can control using mutating funcs:

    struct PurrDecibelView {
        var intensity: Double
    
        mutating func increaseIntensity() {
            intensity += 1
        }
    }
    
    extension PurrDecibelView: View {
        var body: some View {
            Text("")
        }
    }
    

    3. Styleguide

    Some teams and some companies prefer to always use var inside the structs and only control the mutability of the initiated objects.

    💡 Not that I don't personally recommend or deny any of the above or any other reasons.