Computed Property uses getter and setter Methods to compute (store & retrieve) values from other Variables/Methods.
Even though they are just Methods you reference them as if they were Variables.
get can be omitted if there is no set.
Only implicit getter
var greet : String { "Hello John" } //Return can be ommited for single line
print(greet)
Explicit getter & setter
//DECLARE VARIABLES.
var name : String = "" //Normal Variable where value is acctualy stored
//DECLARE COMPUTED PROPERTY.
var greet : String {
get { return "Hello \(name)" } //Composes greeting
set { name = newValue } //Stores new name (newValue is default). set (myValue) {...}
}
//REFERENCE COMPUTED PROPERTY.
greet = "John" //Calls set which stores "John" into name Variable
print(greet) //Calls get which returns "Hello John" by using name Variable
Computed Property returns Closure
//DECLARE COMPUTED PROPERTY.
var greet : (String, Int) -> (String) { //Only has get
var closure : (String, Int) -> (String) = { name, age in return("\(name) is \(age) years old") }
return(closure)
}
//REFERENCE COMPUTED PROPERTY.
var closure : (String, Int) -> (String) = greet //Calls get which returns Closure.
var result = closure("John", 50) //Call Closure
print(result)
Property Observers are methods that can be added to any variable, constant or field
● Method willSet (newValue) is called before the new value is stored
● Method didSet (oldValue) is called after the new value is stored
Property Observer Syntax
var name : String = "John" {
willSet { print("Name will be changed from \(name) to \(newValue)") } //willSet (newValue) {...}
didSet { print("Name was changed from \(oldValue) to \(name)" ) } //didSet (oldValue) {...}
}
name = "Bill"