What is this variable-function hybrid thing?

Code Block
var sum: Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
return orderAmount / peopleCount * tipSelection
}

Is this a function, a variable, or both?
Answered by Claude31 in 639413022
This is a computed var.

you invoke simply by a direct call.
Code Block
print("sum is", sum)

When you use the var, the closure is executed and returns the computed value in the var itself.

The equivalent func would be
Code Block
func sum() -> Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
return orderAmount / peopleCount * tipSelection
}

Code Block
print("sum is", sum())

With a func you can add parameters, what you can't do with computed var

Code Block
func sum(numberOfPeople: Int) -> Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
return orderAmount / peopleCount * tipSelection
}


Accepted Answer
This is a computed var.

you invoke simply by a direct call.
Code Block
print("sum is", sum)

When you use the var, the closure is executed and returns the computed value in the var itself.

The equivalent func would be
Code Block
func sum() -> Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
return orderAmount / peopleCount * tipSelection
}

Code Block
print("sum is", sum())

With a func you can add parameters, what you can't do with computed var

Code Block
func sum(numberOfPeople: Int) -> Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
return orderAmount / peopleCount * tipSelection
}


Thanks, Claude31. This computed variable thing is new to me.
What is this variable-function hybrid thing?
 
 
Q