drewpotential
drewpotential

Reputation: 43

What type of variable Declaration is this in Swift

I'm new to swift, and have been trying to find the definition for this type of instantiation, but have had no luck. I saw something similar in an example project. What is this called?

Example:

var str = "Hello World"

var test: Int {
    var testVal = 5

    if !str.isEmpty {
       testVal = 10
    }
    return testVal
}

In XCode playground, this will show the value for str but not for test. Not until you type test on a new line, or use it elsewhere. I thought it was an example of an autoclosure, but that has a more deliberate syntax, and immediately runs.

Example of autoclosure with shortcut syntax:

var str = "Hello World"

var test: Int = {
    var testVal = 5

    if !str.isEmpty {
       testVal = 10
    }
    return testVal
}()

This latter example will define test right away, and you'll see the output in playground, for instance. The advantage of the former is that, for more complex situations, it will delay defining the value

Upvotes: 2

Views: 108

Answers (2)

Lorenzo Zanotto
Lorenzo Zanotto

Reputation: 163

It's a Computed Property.

Computed properties defer to stored properties in the way you assign a value to the property (or variable) itself. In your case the str variable is a stored property since you're assigning a value without further operations on the value itself.

If you examine the test variable you notice that to assign a value you need to perform further operations and then return the actual piece of information you want to store. Computed properties can also return the value of a stored property as well and they provide a getter and an optional setter to themselves.

Upvotes: 1

atreat
atreat

Reputation: 4403

Your first example is a 'Computed Property', every time that variable is accessed the closure is run. This is how you can override the getter and setters of a property. In your code above, having a single closure implicitly defines that as the getter. You could also do:

var test: Int {
  get {
    var testVal = 5

    if !str.isEmpty {
      testVal = 10
    }
    return testVal
  }
  set(value) {
    test = value
  } 
}

Your second example is simply defining a closure that is executed immediately. This closure will only be run once when the object is initialized. It is useful to follow this pattern when you want to have computed properties that are 'lazy'. When lazy, the closure would be run once when the property is first accessed, not when the object is initialized.

The syntax looks very similar, but the ideas of computer properties and lazy properties have subtle differences. It is important to note that computer properties can not be marked as lazy.

Upvotes: 4

Related Questions