Swift - Class Computed properties

Introduction

You can create properties that use code to calculate their value.

These are known as computed properties.

For example, consider a class that represents a rectangle, which has both a width and a height property.

The area property can be a computed property, which looks like a regular property from the outside, but it is really a function that figures out the value when needed.

To define a computed property, you declare a variable in the same way as you do for a stored property, but add braces { and } after it.

Inside these braces, you provide a get section and a set section:

class Rectangle { 
    var width: Double = 0.0 
    var height: Double = 0.0 

    var area  : Double { 
        // computed getter 
        get { 
            return width * height 
        } 

        // computed setter 
        set { 
            // Assume equal dimensions (i.e., a square) 
            width = newValue.squareRoot() 
            height = newValue.squareRoot() 
        } 
    } 
} 

When creating setters for your computed properties, you are given the new value passed into the setter as a constant called newValue.

In the previous example, we computed the area by multiplying the width and height.

The property is settable.

if you set the area of the rectangle, the code assumes that you want to create a square and updates the width and height to the square root of the area.

Demo

class Rectangle { 
    var width: Double = 0.0 
    var height: Double = 0.0 

    var area  : Double { 
        // computed getter 
        get { /*  ww  w .j a v a2  s  . co m*/
            return width * height 
        } 

        // computed setter 
        set { 
            // Assume equal dimensions (i.e., a square) 
            width = newValue.squareRoot() 
            height = newValue.squareRoot() 
        } 
    } 
} 
let rect = Rectangle() 
rect.width = 3.0 
rect.height = 4.5 
print(rect.area)

rect.area = 9 // width & height now both 3.0 
print(rect.width)
print(rect.height)

Result

Related Topic