The professor codes like this in the lecture
var number: Int { return 3 }
what's different about this?
var number: Int = 3
In practice number is 3 when you use it, such as
let newNumber = number
Behind the scene it is quite different.
var number: Int = 3
You assign a value of 3 to the var. You can later change its value at will. number = 4
var number: Int { return 3 }
Is a so called computed var When you get the var, you execute the closure. Test this
var number: Int {
print("I'm number 3")
return 3
}
So you can have a more complex logic:
var three = true
var number: Int {
print("I'm number 3")
return three ? 3 : 4
}
print(number)
You get 3
If you now set
three = false
and call
print(number)
you get 4.
This is very convenient: you can now use number without worrying about var as three
: everything is encapsulated in the var itself.
In the same way you can define a setter, to update another var (like an IBOutlet) when the value changes. See details in Swift Reference manual.
Note that you cannot assign anymore a new value directly:
number = 4
will cause error: Cannot assign to value: 'number' is a get-only property. Which shows that such a use is not really useful. It should in such a case be simpler to declare as a const:
let number = 3
The reason is that computed var is just that: a var computed from another var.
For instance, if you want to compute miles per gallon, you will have
var miles : Float = 100
var gallons : Float = 4
var mpg : Float {
return gallons > 0 ? miles / gallons : 0
}
Get more here: https://stackoverflow.com/questions/29690521/set-value-to-computed-properties-in-swift