Composite Type Field Getters and Setters
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.Last updated