Wednesday, July 17, 2019

Property in Swift

1.  Stored or Computed property

In Swift, both struct and class can define properties. There are two types of property, stored property and computed property.

In property definition, if it only contains property name and type, or it is followed by assignment '=', then it is a stored property, as shown below
var stored2 : Int
var stored1 : Int = 0
var stored3 : String = { return "hi"}()

If after the variable name and type,  and immediately followed with a curly bracket, then within the curly bracket, if it only contains willSet and/or didSet, then it is still a stored property.
     var m :Int  {
         willSet {
             print("The value is changed from \(m) to \(newValue)")
         }
         didSet {
            print("The value is changed from \(oldValue) to \(m)")
         }
    }

But if within the curly bracket it contains get and/or set, or it only contains a closure expression (for the shorthand get accessor), then it is a computed property.
   var computed :Int {
        get {
             return m
        }
        set (newValue) {
            m = newValue
       }
  }

  var computed2: Int {
      return m
 }

2. Initialize stored property with closure
Usually, stored property can be initialized by assigning it to a new object as shown below
var myComplex : UIViewController = UIViewController()

But it can also be initialized by using a closure expression with parameters in the ending parenthesis as shown below 
var myComplex2 : [Int] = { return Array(repeating: $0, count: $1)}( 5, 6)

Note this is quite similar to readonly computed property, although the assignment operator indicates it is a stored property

3. Stored property only attribute
willSet, willGet accessor can only applied to stored properties, and cannot apply to computed property, as for computed property, developer can add any logic in the get/set accessors, and there is no need to use willSet/willGet accessors.

For the similar reason, lazy property can only apply to stored properties. In addition, lazy property should be defined as no-optional type properties, instead of optional type, and it must be defined as var instead of let.

The reason to use lazy property is, usually in the init method, all no-option stored properties should be initialized. However, if a property is defined as lazy, it is not required to be initialize in init method. The lazy property's value will be set when it is used first time.
lazy var lazyBoy : ComplexData = ComplexData()

In multiple thread situation, if multi threads access the lazy property at the same time, the property may be initialized more than once.

Lazy property should not be applied to struct, as it will requires the struct can only be used by var instead of let.
 

No comments:

Post a Comment