Swift - Using Computed Properties

Introduction

Computed properties enable you to set or retrieve another property's value.

Using the same Point class, you now have the additional computed property called newPosition :

class Point {
    var x = 0.0
    var y = 0.0
    let width = 2
    var newPosition:(Double, Double) {
         get {
             return  (x, y)
         }
         set (position) {    //position is a tuple
             x = position.0  //x
             y = position.1  //y
         }
     }
}

The newPosition property is a computed property.

It accepts and returns a tuple containing two Double values.

To use the newPosition property, you can assign it a tuple:

var ptB = Point()

//assign a tuple to the newPosition property

ptB.newPosition = (10.0,15.0)
print(ptB.x) //10.0
print(ptB.y) //15.0

When you assign it a value, the set block of the code is executed:

set (position) {    //position is a tuple
    x = position.0
    y = position.1
}

Here, the position represents the tuple that you have assigned (10.0,15.0)

position.0 represents the first value in the tuple 10.0 and position.1 represents the second value in the tuple 15.0.

You assign these values to the x and y properties, respectively.

When you try to access the newPosition property, as shown here:

var position = ptB.newPosition
print(position.0)  //10.0
print(position.1)  //15.0

it will execute the get block of code:

get {
    return  (x, y)
}

Here, it returns the value of x and y using a tuple.

Because the newPosition property does not store any value itself, but rather stores the value assigned to it in another property, it is known as a computed property.

Structures also support computed properties.

Related Topic