Composite Type Field Getters and Setters

🚧 Status: Field getters and setters are not implemented yet.

Fields may have an optional getter and an optional setter. Getters are functions that are called when a field is read, and setters are functions that are called when a field is written. Only certain assignments are allowed in getters and setters.

Getters and setters are enclosed in opening and closing braces, after the field's type.

Getters are declared using the get keyword. Getters have no parameters and their return type is implicitly the type of the field.

pub struct GetterExample {

    // Declare a variable field named `balance` with a getter
    // which ensures the read value is always non-negative.
    //
    pub var balance: Int {
        get {
           if self.balance < 0 {
               return 0
           }

           return self.balance
        }
    }

    init(balance: Int) {
        self.balance = balance
    }
}

let example = GetterExample(balance: 10)
// `example.balance` is `10`

example.balance = -50
// The stored value of the field `example` is `-50` internally,
// though `example.balance` is `0` because the getter for `balance` returns `0` instead.

Setters are declared using the set keyword, followed by the name for the new value enclosed in parentheses. The parameter has implicitly the type of the field. Another type cannot be specified. Setters have no return type.

The types of values assigned to setters must always match the field's type.

pub struct SetterExample {

    // Declare a variable field named `balance` with a setter
    // which requires written values to be positive.
    //
    pub var balance: Int {
        set(newBalance) {
            pre {
                newBalance >= 0
            }
            self.balance = newBalance
        }
    }

    init(balance: Int) {
        self.balance = balance
    }
}

let example = SetterExample(balance: 10)
// `example.balance` is `10`

// Run-time error: The precondition of the setter for the field `balance` fails,
// the program aborts.
//
example.balance = -50

Last updated