Have any Question?

You can ask below or enter what you are looking for!

How to create a Computed property in Swift

What is a computed property

Classes, Structures and Enums may define a computed property.

It is a property that does not store value, instead it defines getter and setter to retrieve and set other properties and values indirectly.

The setter is optional, if you define a getter only then this computed property will be read-only.

How to define a computed property

Lets see how to define and use a computed property by example

struct Time {
    
    var seconds: Double = 0.0
    
    var minutes: Double {
        
        get {
            return seconds / 60.0
        }
        set {
            self.seconds = newValue * 60.0
        }
    }
    
    init(seconds: Double) {
        self.seconds = seconds
    }
    
}

That was a struct that contain one stored property- seconds- and one computed property – minutes- which is computed by dividing seconds by 60.

In the setter you notice that we used a newValue name, this is the default name for the new value if you didn’t specify one. Lets see how to use our computed property in code

        var time = Time(seconds: 150.0)
        print("seconds: \(time.seconds)")
        print("minutes: \(time.minutes)")
        
        time.minutes = 5
        print("seconds: \(time.seconds)")

Result

seconds: 150.0
minutes: 2.5
seconds: 300.0

First we created a Time variable with 150 seconds When we printed the minutes property it was computed by dividing 150/ 60 = 2.5

When we  set the minutes property to 5 the setter changes the seconds by multiplying 5 * 60 = 300

Leave a Reply

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