N
N
NONAME82018-07-21 19:08:52
Swift
NONAME8, 2018-07-21 19:08:52

I do not quite understand the principle of computed properties?

I remember after I tried to learn objective-c, I had a certain conviction that when we create a variable like: var per = 5 , then get and set methods work to create it.
But when I started to deal with computed properties, I realized that they do not store values ​​and the set and get methods do not work with the immediate variable where they are implemented.
And then I had a few questions:
Are there any setters and getters that work with the variable itself when it is created?
Or are these setters and getters just extra functionality that is used for computational properties?
And we create a variable without them, but usually?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Cherny, 2018-07-21
@NONAME8

Each class variable has memory allocated to it, but computed properties do not. In the getter and setter, you simply define some kind of expression that is executed in the corresponding operation. Good example over time:

class Time {
    var seconds:Double = 0
    
    init(seconds: Double) {
        self.seconds = seconds
    }
    
    var minutes: Double {
        get {
            return (seconds / 60)
        }
        set {
            self.seconds = (newValue * 60)
        }
    }
    
    var hours: Double {
        get {
            return (seconds / (60 * 60))
        }
        set {
            self.seconds = (newValue * (60 * 60))
        }
    }
    
    var days:  Double {
        get {
            return (seconds / (60 * 60 * 24))
        }
        set {
            self.seconds = (newValue * (60 * 60 * 24))
        }
    }
}

It's just an abstraction, of course you can use a function instead, but in some cases it's more "elegant" or something ..
A good measurement is also in the iBook Swift book with a rectangle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question