[SwiftUI] When to use closures vs equals for variable assignment?

Hi, I'm new to swift but have experience with coding in general. Following the app dev training tutorial, came across this line of code:

  var wrapper: ErrorWrapper {
        ErrorWrapper(error: someVal)
    }

My question is, why not just do this...

  var wrapper: ErrorWrapper =  ErrorWrapper(error: someVal)

Is it a conventions thing or is there some purpose, code seems to work either way. My understanding of closures is that they are just lambda functions, so in the first codeblock, all it's doing is calling a function that returns the instantiated ErrorWrapper object. Why not just assign the variable to it?

Answered by Claude31 in 797179022

It is not a convention, it is a major difference.

The difference is that computed var (first option) is evaluated each time the var is accessed. So it can change on the fly. The second option is initialised once for all.

Consider the simple case:

var myVar: Int {
    (0...10).randomElement()!
}

var myVar2 = (0...10).randomElement()!

for _ in 0...3 {
    print(myVar, myVar2)
}

You get:

5 4
1 4
4 4
7 4
Accepted Answer

It is not a convention, it is a major difference.

The difference is that computed var (first option) is evaluated each time the var is accessed. So it can change on the fly. The second option is initialised once for all.

Consider the simple case:

var myVar: Int {
    (0...10).randomElement()!
}

var myVar2 = (0...10).randomElement()!

for _ in 0...3 {
    print(myVar, myVar2)
}

You get:

5 4
1 4
4 4
7 4
[SwiftUI] When to use closures vs equals for variable assignment?
 
 
Q