Swift Introduction | Class Basics | Computed Properties

In addition to inheritance, there are several other features to remember. This article explains computed properties.

A property is a variable that stores a value in a class. Because its value can be replaced directly, it can hold any permitted value. A computed property lets you control reading and writing through code.

Write a computed property as follows.

var property : Type {
    get {
        ... processing ...
        return value
    }
    set {
        ... processing ...
    }
}

After the property declaration, write braces containing get and set blocks that define how to read and write the value. If you provide only get, the property is read-only.

The following example uses a computed property.

class Friend {
    var name:String

    var old:Int

    var age:Int {
        get {
            return old
        }
        set {
            if newValue > 0 {
                old = newValue
            }
        }
    }

    init(name:String, age:Int) {
        self.name = name
        self.old = age
    }

    func printData() {
        print("\(self.name) (\(age))")
    }
}

var you = Friend(name: "Taro", age: 30)
you.printData()

This example uses a computed property named age. The actual value is stored in the old property. A computed property needs a separate location when it stores an underlying value.