Contents Open

DocsLanguage Guide

Properties

Stored and computed properties, observers, field-backed accessors, lazy and static properties.

Properties associate values with a structure, class, actor, union or enum. A stored property keeps a value as part of each instance. A computed property keeps nothing: it works its value out each time it is read, and may take a new one when it is written. Sable adds two forms between those: a field-backed property, stored but read and written only through its accessors, and a lazy property, computed once on first use and then kept.

You can also observe a stored property, running code each time it changes, and declare type properties that belong to the type itself rather than to any one instance.

Stored Properties#

The fields you met in Structures and Classes are stored properties. A var can change after the instance is made; a let, or a field written bare as name: Type, can't:

Sable
struct FixedLengthRange {    var firstValue: Int    let length: Int}var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)// the range represents 0, 1 and 2rangeOfThreeItems.firstValue = 6// the range now represents 6, 7 and 8

A stored property may give an initial value, var interlaced = false, which every initialiser starts from. One without an initial value must be set by every initialiser before it returns; reading a property before it has been set is an error, never a silent zero.

Stored properties of constant structures#

A struct held in a let can't be changed at all, even through its var properties:

Sable
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)rangeOfFourItems.firstValue = 6     // error: the left side must be a mutable binding

This follows from structs being values: changing a field is changing the value, and a let value never changes. A class is different. A let holding an object fixes which object it is, and the object's var properties can still be set through it.

Computed Properties#

A computed property provides a getter, and optionally a setter, instead of storing a value:

Sable
struct Point { var x = 0.0, var y = 0.0 }struct Size { var width = 0.0, var height = 0.0 }struct Rect {    var origin = Point()    var size = Size()    var center: Point {        get {            let centerX = origin.x + size.width / 2            let centerY = origin.y + size.height / 2            return Point(x: centerX, y: centerY)        }        set(newCenter) {            origin.x = newCenter.x - size.width / 2            origin.y = newCenter.y - size.height / 2        }    }}var square = Rect(origin: Point(x: 0, y: 0), size: Size(width: 10, height: 10))let initialCenter = square.centersquare.center = Point(x: 15, y: 15)print("square.origin is now at (\(square.origin.x), \(square.origin.y))")// prints square.origin is now at (10.0, 10.0)

Reading square.center runs the getter; assigning to it runs the setter with the assigned value. A computed property always has an explicit type, and is always declared with var, since its value isn't fixed.

Shorthand setter declaration#

If a setter doesn't name its incoming value, it is called newValue:

Sable
var center: Point {    get {        return Point(x: origin.x + size.width / 2, y: origin.y + size.height / 2)    }    set {        origin.x = newValue.x - size.width / 2        origin.y = newValue.y - size.height / 2    }}

Accessors written with =>#

Either accessor may be written => expression instead of a block, as a function can. A getter's expression is the value; a setter's is an assignment:

Sable
class Box {    var n: Int = 0    var doubled: Int {        get => n * 2        set => n = newValue / 2    }}

Read-only computed properties#

A computed property with a getter and no setter is read-only: it can be read but not assigned. You can write it with get alone, var area: F64 { get => width * height }, but the idiomatic form drops the braces and the keyword too, leaving => and the value:

Sable
struct Cuboid {    var width = 0.0, var height = 0.0, var depth = 0.0    var volume: F64 => width * height * depth}let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")// prints the volume of fourByFiveByTwo is 40.0

var volume: F64 => … means exactly var volume: F64 { get => … }.

Changing part of a computed property#

When you change part of a computed property, Sable reads it through the getter, changes the copy, and writes the result back through the setter, once:

Sable
square.center.x += 5        // get center, add 5 to its x, set center

The same happens when you call a mutating method on it or pass it inout: one read, one write, however deep the change goes.

Property Observers#

Property observers watch a stored property and respond to changes in its value. There are two:

  • willSet runs just before the new value is stored. It sees the incoming value as newValue, or under a name you give it, willSet(name).
  • didSet runs just after. It sees the value that was replaced as oldValue.
Sable
class StepCounter {    var totalSteps: Int = 0 {        willSet(newTotalSteps) {            print("About to set totalSteps to \(newTotalSteps)")        }        didSet {            if totalSteps > oldValue {                print("Added \(totalSteps - oldValue) steps")            }        }    }}let stepCounter = StepCounter()stepCounter.totalSteps = 200// About to set totalSteps to 200// Added 200 stepsstepCounter.totalSteps += 160// About to set totalSteps to 360// Added 160 steps

A store to the property calls willSet, stores the value, then calls didSet. Compound assignment such as += stores through the observers too, and so does changing part of the property's value: setting a field of an observed struct, or calling a mutating method on it, runs each observer once.

When observers don't run#

Inside its own observers, and inside its type's initialisers, an observed property names its storage directly. So:

  • An observer's own changes aren't observed. A didSet may correct the value it was given without running again:

    struct AudioChannel {
        static let thresholdLevel = 10
        var currentLevel: Int = 0 {
            didSet {
                if currentLevel > AudioChannel.thresholdLevel {
                    currentLevel = AudioChannel.thresholdLevel     // no second didSet
                }
            }
        }
    }
    
    var left = AudioChannel()
    left.currentLevel = 11
    print(left.currentLevel)
    // prints 10
  • Initialisers aren't observed. While a value is being made, setting its properties stores them without calling observers. A record literal and a memberwise initialiser set the property the same way.

Rules for observed properties#

An observed property must be a var (an observer runs when it is written, so it must be writable), must not declare get or set of its own, and must belong to a struct, class or actor (S3140). To react to a computed property changing, put the code in its setter instead.

Field-Backed Properties#

Sometimes a property wants to be stored, but to have a say in how it's read or written: trimming a string as it's set, clamping a number. In Swift you would declare a second, private stored property to hold the value. In Sable the accessors can use field, storage that belongs to the property itself and that only its accessors can name:

Sable
struct Account {    var owner: String = "" {        get => field        set => field = newValue.trimmed()    }    var limit: Int = 100 {        get        set { field = newValue < 0 ? 0 : newValue }    }}var account = Account()account.owner = "  Ada  "account.limit = -5print("[\(account.owner)] \(account.limit)")// prints [Ada] 0

The property is stored, laid out with the type's other fields, so it starts from its initial value and must have one. But every read and write goes through its accessors. The rules:

  • get written alone is the plain getter, get => field. set written alone is the plain setter, set => field = newValue. So limit above customises only how it's set.
  • An accessor the property doesn't declare, it doesn't have, as for any computed property: a field-backed property with only a get is read-only.
  • Descriptions and reflection show the storage under the property's name: print(account) prints Account(owner: "Ada", limit: 0).
  • An extension can't add one, since field is storage and extensions can't add stored properties.

Lazy Properties#

A lazy property is computed from its initialiser the first time it is read, and the result is kept for every read after. Mark it lazy var:

Sable
fn splitWords(_ text: String) -> String[>..] {    print("splitting")    return text.split(separator: ' ')}struct Document {    var text: String    lazy var words: String[>..] = splitWords(text)}var doc = Document(text: "the quick brown fox")print("made")print(doc.words.count)print(doc.words.count)
madesplitting44

Laziness is useful when the value is expensive and may never be needed, or depends on other parts of the instance. The initialiser of a lazy property may use self, as a method does; above, text is self.text. Assigning to a lazy property replaces its value, computed or not.

A lazy property must be a var, must have an initialiser, must have no accessors of its own, and must belong to a struct, class or actor (S3113).

Note

The first read of a struct's lazy property writes the struct. So it can only be read where the struct may change: from a var, or inside a mutating method (S3041). Reading doc.words through a let doc is an error. On a class this doesn't arise, since the object can always be written through its reference.

Type Properties#

Instance properties belong to each instance. Type properties belong to the type, with one value shared by all of it. You declare them with static:

Sable
struct SomeStructure {    static let storedTypeProperty = "Some value."    static var counter = 0    static var computedTypeProperty: Int => 1}SomeStructure.counter += 1print(SomeStructure.storedTypeProperty)// prints Some value.

You read and write them through the type's name, or through Self inside the type. A stored type property must have an initial value, since no initialiser sets it. Its type may be left out only when that value is a literal, an array of literals, or a call to a type's initialiser; otherwise write it (S2001): static let unit: Shape = Shape.Rect(width: 1, height: 1).

When type properties are set#

Static stored properties, like module-level lets and vars, are given their initial values once, on one thread, before main begins. After that, reading one costs nothing but the read: there is no lazy-initialisation check, unlike Swift's globals.

The order is worked out for you. Each one is set after the ones its initial value reads, directly or through the functions it calls; otherwise they're set in the order they're written, the standard library's first:

Sable
fn load(_ name: String) -> Int {    print("loading \(name)")    return 1}static let first: Int = second + 1      // reads second, so second goes firststatic let second: Int = load("second")

Two that need each other can't be ordered, and that is an error (S3411). For a value worked out only when it is first asked for, use a lazy property instead.

Setting Access Separately#

A property's setter can be less visible than its getter. private(set) makes a property readable wherever the property is visible, but writable only inside the type:

Sable
struct Ledger {    private(set) var entries: Int = 0    mutating fn record() { entries += 1 }}var ledger = Ledger()ledger.record()print(ledger.entries)       // prints 1ledger.entries = 10         // error: its setter is private (S3010)

The visibility levels themselves are covered in Modules and Access Control.

Accessor Blocks and Trailing Closures#

A property's accessors follow its initial value in braces, as with var totalSteps: Int = 0 { willSet … }. But a brace after an expression is normally a trailing closure. Sable tells them apart by the first token inside: a brace directly after a field's initialiser opens an accessor block when it starts with get, set, willSet or didSet, and is a trailing closure otherwise.

Sable
var tracked: Int = 0 { willSet { } }     // accessorslet handler = makeHandler { }            // a trailing closure passed to makeHandler

Key Paths to Properties#

A key path names the way from a value to one of its properties, as a value of its own. You write it with a backslash:

Sable
struct Customer {    var name: String    var city: String}let byCity = \Customer.citylet ada = Customer(name: "Ada", city: "London")print(byCity.value(of: ada))// prints London

Key paths reach stored and computed properties alike, and can stand in for a function: people.map(\.name). They're covered in Casting, Metatypes and Reflection.

Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.