Swift - Read-Only Computed Properties

Introduction

A computed property with a getter but no setter is known as a read-only computed property.

A read-only computed property can be accessed but not set.

The following shows the newPosition computed property without the setter:

class Point{
    var x = 0
    var y = 0
    
    var newPosition:(Double, Double) {
      get {
          return  (x, y)
      }
    }
    
}    

A read-only computed property can also be simplified without the use of the get keyword:

var newPosition:(Double, Double) {
    return  (x, y)
}

In either case, you can no longer set a value to the newPosition property:

var ptB = Point()
ptB.x = 25.0
ptB.y = 50.0
//assign a tuple to the newPosition property
ptB.newPosition = (10,15)  //error

If a computed property has a setter, it must have a getter.

Related Topic