Skip to content
KYND Dev

Advanced Swift: Computed Properties and Observed Properties

iOS, Mobile1 min read

Computed Properties

When we want to calculate the value of property base on other properties. The value of this property will auto update when other properties updated

1let basicSalary = 1000
2var monthyAllowance = 300
3var totalSalary: Int {
4 get {
5 return basicSalary + monthyAllowance
6 }
7}

Observed Properties

When we don’t need to calculate the value of property but just monitor when the value is change

1let totalSalary: Int = 1000 {
2 // Right before the property get change => willSet function will trigger
3 willSet{
4 print(newValue) // newValue: The value will be set to
5 }
6 // Right after the property get change => didSet function will trigger
7 didSet{
8 // We can check whether property value is valid or not
9 print(oldValue) // oldValue: The value that this property used to be
10 if totalSalary <= MIN_SALARY:
11 totalSalary = MIN_SALARY
12 }
13}