Properties in swift

There are several properties such as:

  1. Stored properties
    • Lazy stored properties
  2. Computed properties
    • get
    • set
  3. Observers properties
    • didSet
    • willGet

1. Stored properties:

Stored properties are those values that are contained within a constant or variables.

Such as:

var userName: string = "Joynal Abedin"
let countryName: string = "Bangladesh"

1.1. Lazy stored properties:

When a property is declared as being lazy, it is only initialized when it is first accessed, allowing any resource intensive activities to be deferred until the property is needed and any initialization on which the property isdependent to be completed.
Note that lazy properties must be declared as variables (var).

class MyClass {
      
      lazy var myProperty: String = {
            var result = MyModel()
            return result
      }()
}

2. Computed properties:

A computed properties is value that is devrived based on some form of calculation or logic at the point at which the property is set or retrieved. Computed properties are implemented by creating getter and optional corresponding setter methods containing the code to perform the computation.

var totalAmount: Float {

       get {
            return previousAmount - newAmount
       }

       set(newBalance) {
           accountBalance = newBalance - fees
       }
}

3. Observer properties:

class Account {
      
      var accountBalance: Double {
           didSet {
               print("This message will sent after set accountBalance")
           }
           
           willSet {
               print("This message will sent before set accountBalance")
           }
      }
}

Note that, didSet will notify after set values & willSet will notify before set values.

438 thoughts on “Properties in swift

Leave a Reply

Your email address will not be published. Required fields are marked *