DocsLanguage Guide
Methods, Subscripts and Operators
Instance and static methods, mutating methods, subscripts, and overloading operators.
Methods are functions that belong to a type. Instance methods are called on an instance and work with it; static methods are called on the type itself. Structures, classes, actors, unions and enums can all define both, which is a difference from C, where data and the functions on it are kept apart.
Types can also define subscripts, which let you reach into an instance with brackets, matrix[0, 1], and operators, which let +, == or [] work on your own types. This chapter covers all three.
Instance Methods#
You write an instance method inside the type's braces, with the same fn syntax as any function:
class Counter { var count = 0 fn increment() { count += 1 } fn increment(by amount: Int) { count += amount } fn reset() { count = 0 }}let counter = Counter()counter.increment()counter.increment(by: 5)print(counter.count)// prints 6You call a method with dot syntax. Everything you learned about parameters applies: argument labels, default values, overloading on labels and types (both increment methods live side by side above), throwing and async.
The self property#
Every instance has an implicit property called self, which is the instance itself. Inside a method you can write self.count, but you rarely need to: a name inside a method is looked up among the type's members when no local or parameter has it.
The exception is when a parameter has the same name as a property. Then the parameter wins, and self reaches the property:
struct Point { var x = 0.0, var y = 0.0 fn isToTheRight(of x: F64) -> Bool { return self.x > x }}let somePoint = Point(x: 4.0, y: 5.0)print(somePoint.isToTheRight(of: 1.0))// prints trueMutating Methods#
Structures, unions and enums are value types, and by default a method can't change the value it was called on. Mark a method mutating when it needs to:
struct Point { var x = 0.0, var y = 0.0 mutating fn moveBy(x deltaX: F64, y deltaY: F64) { x += deltaX y += deltaY }}var somePoint = Point(x: 1.0, y: 1.0)somePoint.moveBy(x: 2.0, y: 3.0)print("The point is now at (\(somePoint.x), \(somePoint.y))")// prints The point is now at (3.0, 4.0)The keyword is required: assigning to a field in a method without it is an error (S3010). And because a mutating method changes its value, it can only be called on one that can change: calling moveBy on a let point is an error (S3041). Classes don't need mutating. A method of a class changes the object through its reference, which a let doesn't forbid.
Assigning to self#
A mutating method can replace the whole value by assigning to self:
struct Point { var x = 0.0, var y = 0.0 mutating fn moveBy(x deltaX: F64, y deltaY: F64) { self = Point(x: x + deltaX, y: y + deltaY) }}For an enum or union, assigning to self is how a method moves the value to another case:
enum TriStateSwitch { Off, Low, High mutating fn next() { self = match self { case .Off => .Low case .Low => .High case .High => .Off } }}var ovenLight = TriStateSwitch.LowovenLight.next()print(ovenLight)// prints HighovenLight.next()print(ovenLight)// prints OffStatic Methods#
A static method belongs to the type rather than to an instance. Declare it with static fn, and call it on the type:
struct LevelTracker { static var highestUnlockedLevel = 1 static fn unlock(_ level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static fn isUnlocked(_ level: Int) -> Bool { return level <= highestUnlockedLevel }}LevelTracker.unlock(3)print(LevelTracker.isUnlocked(2))// prints trueInside a static method, other static members are named without the type, as highestUnlockedLevel is above. A static method is often a named way to make a value, where an initialiser's labels wouldn't say enough. Self stands for the enclosing type, so such a method doesn't need to repeat its name:
struct Vec3 { var x: F32, var y: F32, var z: F32 static fn splat(_ v: F32) -> Self { return Self(x: v, y: v, z: v) }}let ones = Vec3.splat(1)Subscripts#
A subscript is a shortcut for reaching an element of a collection, a sequence or anything that has parts: someArray[index], someDictionary[key]. You can define subscripts on your own types with subscript. A subscript looks like a computed property with parameters: it has a getter, and optionally a setter.
struct Matrix { let rows: Int, let columns: Int var grid: F64[>..] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns self.grid = F64[>..](repeating: 0.0, count: rows * columns) } subscript(row: Int, column: Int) -> F64 { get => grid[(row * columns) + column] set { grid[(row * columns) + column] = newValue } }}var matrix = Matrix(rows: 2, columns: 2)matrix[0, 1] = 1.5matrix[1, 0] = 3.2print(matrix[1, 0])// prints 3.2matrix[0, 1] = 1.5 calls the setter with newValue set to 1.5; matrix[1, 0] calls the getter. A subscript can take any number of parameters of any types, and can return any type. As with properties, a setter can name its value with set(name), and compound assignment works through the getter and setter: matrix[0, 1] += 1 reads once and stores once.
Read-only subscripts#
A subscript with no setter is read-only. Like a read-only property, it can drop the get and the braces and give its value after =>:
struct TimesTable { let multiplier: Int subscript(index: Int) -> Int => multiplier * index}let threeTimesTable = TimesTable(multiplier: 3)print("six times three is \(threeTimesTable[6])")// prints six times three is 18Labelled subscripts#
Subscript parameters are unlabelled at the call by default, unlike a function's. Give a parameter an argument label and the call must write it, which lets one type have several subscripts that mean different things:
struct Matrix { // ... subscript(row r: Int) -> F64[:] => grid[r * columns ..< (r + 1) * columns]}print(matrix[row: 1])// prints [3.2, 0.0]The labels make the subscript say what it does: row[from: 2, or: "none"] reads very differently from row[2].
A reading and a storing subscript#
A type may declare two subscripts with the same labels: one that only reads, and one that reads and stores. Sable picks by use: a store goes to the subscript that stores, and a read to the one that only reads. A collection uses this to make reading cheap while still allowing writes. A type that has only a read-only subscript refuses a store through it (S3010), as a String refuses text[^1] = c.
Operator Overloading#
Types can give meaning to Sable's operators. You declare an operator inside the type with operator, the symbol, and the operands as parameters:
struct Vector2D { var x = 0.0, var y = 0.0 operator + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) }}let vector = Vector2D(x: 3.0, y: 1.0)let anotherVector = Vector2D(x: 2.0, y: 4.0)let combined = vector + anotherVectorprint("\(combined.x), \(combined.y)")// prints 5.0, 5.0A binary operator takes two parameters, the left operand and the right. Unlike a method, an operator has no self: it is a static function of the type, found from the types of its operands. Operators can be declared in extensions and protocols too, and an operator that is short enough can use =>:
operator - (left: Vector2D, right: Vector2D) -> Vector2D => Vector2D(x: left.x - right.x, y: left.y - right.y)Prefix operators#
A unary operator written before its operand is declared prefix operator, with a single parameter:
struct Vector2D { var x = 0.0, var y = 0.0 prefix operator - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x, y: -vector.y) }}let positive = Vector2D(x: 3.0, y: 4.0)let negative = -positiveprint("\(negative.x), \(negative.y)")// prints -3.0, -4.0Compound assignment#
You don't declare +=. Every compound assignment is derived from its binary operator: once + is defined, += works, and -= works only once - is.
var original = Vector2D(x: 1.0, y: 2.0)original += Vector2D(x: 3.0, y: 4.0)print("\(original.x), \(original.y)")// prints 4.0, 6.0A compound assignment works out what its target is made of once, before the right side: xs[next()] += f() calls next once, reads that element, calls f, and stores where it read.
Indexing and calling operators#
Two operators turn an instance into something you index or call. operator [] is another way to declare a subscript, and operator () makes an instance callable like a function:
struct Money { var cents: Int operator [] (m: Money, unit: String) -> Int => unit == "dollars" ? m.cents / 100 : m.cents operator () (m: Money, times: Int) -> Money => Money(cents: m.cents * times)}let price = Money(cents: 250)print(price["dollars"])// prints 2print(price(times: 3).cents)// prints 750The first parameter is the instance; the rest are what goes between the brackets or parentheses.
Which operators can be overloaded#
| Can be overloaded | Can't be overloaded |
|---|---|
Binary + - * / % & | ^ << >> |
&&, || and ?? (they short-circuit) |
Comparison == != < <= > >= |
?., ., = |
Indexing [] and calling () |
as, is |
Prefix - ! ~ |
Compound assignment (derived instead) |
Sable has no custom operators: you can't declare a new symbol such as +++ or <=>. And an operator's precedence and associativity are fixed by the grammar, the same for your types as for numbers, as listed in Basic Operators. This is a deliberate trade against Swift: code using an operator always parses the same way, whatever is imported, and a reader never meets a symbol whose meaning they have to look up.
Equatable and Comparable#
The comparison operators are how you join two of the standard library's most important protocols. Equatable requires one operator, ==; != follows from it. Comparable refines Equatable and is satisfied by <: >, <= and >= have default implementations in terms of it.
So the usual pattern is to declare the conformance, and the two operators:
struct Version: Comparable { var major: Int, var minor: Int operator == (a: Version, b: Version) -> Bool => a.major == b.major && a.minor == b.minor operator < (a: Version, b: Version) -> Bool => a.major < b.major || (a.major == b.major && a.minor < b.minor)}let installed = Version(major: 1, minor: 4)let minimum = Version(major: 1, minor: 10)print(installed < minimum) // prints trueprint(installed >= minimum) // prints falseprint(installed != minimum) // prints trueConforming is what lets generic code use your operators: fn max<T: Comparable>(_ a: T, _ b: T) -> T now works for versions, and so do sorting and searching. Protocols themselves are covered in Protocols.
For a struct like Version, whose equality and order are just its fields' in turn, you needn't write the operators at all: @derive(Equatable, Comparable) has the compiler write them, as covered in Derivation and Source Generators.