2

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?

3
  • No there isn’t. “Let” would make it correct but it doesn’t make a difference. Commented Dec 12, 2023 at 13:37
  • @MojtabaHosseini, I just added the time. Commented Dec 12, 2023 at 13:39
  • Should be let. Always lots of typos in these videos. Commented Dec 13, 2023 at 6:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I completely missed #1, that makes sense. I thought about #2, you could have some ViewBuilder that uses this before returning the view. #3 sound plausible, but would be better with a reference to such a style guide (preferably with a rationale).
As I mentioned, In this answer, I agree or against none of them., but for the #2, imagine a normal Rectangle struct that someday you have decided to make it View-able. And about the reference, I saw this in some companies internally but I can't find a public source to share. I will update you if I can.
Extension of an existing type to conform to View doesn't have anything to do with this question (which already considers a View), but it's an interesting idea!
Yes, I did the extension to be more clear, I kept the naming to be linked with original question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.