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?
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:
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:
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 func
s:
struct PurrDecibelView {
var intensity: Double
mutating func increaseIntensity() {
intensity += 1
}
}
extension PurrDecibelView: View {
var body: some View {
Text("")
}
}
Some teams and some companies prefer to always use var inside the struct
s 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.