Search code examples
swiftinstantiationcomputed-properties

difference between a computed property and setting a function to a variable in Swift


I have these two ways to set a string that I have seen in SO.

I am wondering what the advantage of one over the other is and if anyone can give me a link to an article or documentation of this syntax.

I believe the first is called a computed property and I have read the Computed Property section on swift.org.

I think the second is actually just setting the constant name 'string2" to a closure, but I may not be calling it the right thing, that's why I am asking because I can't really find any articles or documentation on it. Thanks in advance for any help.

var string1: String { return "My first string"}

let string2 = { return "My second string"}()

Solution

  • The code in the computed property gets executed every time you reference that variable. The code in the property initialized by a closure is only executed once, during initialization.