Search code examples
swiftvariablescomputed-properties

Swift: Difference between var a: Int { calculateValue() } and var b = { calculateValue() }()


I am trying to understand the difference between

var a: Int { calculateValue() }

and

var b = { calculateValue() }()

I'm a little confused, but I think I get the basics, so I just wanted to make sure I have it right: Is it that the first one is a computed property that will run calculateValue() every single time I use a somewhere and use that value, whereas the second one just assigns the value of the closure to b at the time of initialisation?

Thank you


Solution

  • A

    var a: Int { calculateValue() } is a computed property, equivalent to:

    var a: Int {
       get { calculateValue() }
    }
    

    The computed body is called everytime a is accessed, which means calculateValue is called on every access (which can be good good, if its value changes, but wasteful if it doesn't)

    B

    { calculateValue() } is a closure of type () -> Int, whose body calls calculateValue. The trailing () calls that closure, which makes it an immediately evaluated closure.

    The result (as assigned to the stored property var b) is just an Int (not at () -> Int, because the closure was already called)