-1

I am trying to understand Computed Properties mostly I have understood the concept but one output is confusing me

struct SomePrices {

    var eighth: Double
    var quarter: Double
    var half: Double
    var zip: Double {    
        get {
            return half * 2  - 20
        }

        set {
            eighth = newValue / 8 + 15
            quarter = newValue / 4 + 10
            half = newValue / 2 + 5
        }
    }
}

var gdp = SomePrices(eighth: 37.0, quarter: 73.0, half: 123.0)
gdp.eighth // 37
gdp.quarter // 73
gdp.half // 123
gdp.zip // 226


gdp.zip = 300
gdp.eighth // 52.5
gdp.quarter // 85
gdp.half // 155
gdp.zip // 290

Been trying to understand how did I get 290 when gdp.zip = 300

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
A Abhishek
  • 77
  • 6
  • 1
    you'd have a much easier time if you just store one reference price (e.g. the price per ounce), and derive the others using computed properties. – Alexander Nov 17 '19 at 16:07

1 Answers1

1

You set zip to 300 so half becomes (300 / 2 + 5) = 155.

half = newValue / 2 + 5

Then you get zip which is (155 * 2 - 20) = 290.

return half * 2 - 20

shbedev
  • 1,875
  • 17
  • 28
  • Hi, check out this link, it should clarify this subject for you - https://stackoverflow.com/questions/24006234/what-is-the-purpose-of-willset-and-didset-in-swift there. – shbedev Nov 17 '19 at 16:31