What makes a property a computed property in Swift

后端 未结 4 1077
Happy的楠姐
Happy的楠姐 2020-12-19 10:38

Let\'s started with the code snippet:

St Foo {
    var proA: Int = 0 { // needs initialization
        willSet {
            print(\"about to set proA to \\(         


        
4条回答
  •  盖世英雄少女心
    2020-12-19 11:02

    a. Yes,a property with only observer is a stored property not a computed property.Beacuase property observer tracks the value of a property whose value has initialised previously & it's now changing ,that's a stored property. It's not applicable for a computed property since it has no predefined value

    b. computed property is a property whose value depends on other variables, we should declare only those properties as computed property , who needs to be computed using value of another variables ,so it's value cannot be initialised in advance. for e.g. - If we have 2 variables a & b. we need their addition value , so a variable named 'sum' is used , then sum will be declared as a computed property & its get{} block will return (a+b) that's sum of a & b & the value of sum variable.Then in this case we can't initialise property 'sum' in advance because it will be computed using a & b.

    c. Setter is not an observer it sets value of another variable or performs some actions related to other variables whereas a property observer tracks changes in value of its associated variable itself. for e.g. it's meaningless to use a property observer for variable 'sum' as described in point b .

提交回复
热议问题