DocsLanguage Guide
Extensions
Adding members and conformances, constrained extensions, and extending every array.
An extension adds members to a type that already exists: methods, computed properties, initialisers, subscripts, operators, nested types and protocol conformances. It works on types you wrote, on library types, and on the built-in ones — String, Int, and every kind of array.
Extensions are how Sable code is usually organised. A type's core — its stored properties and main initialisers — goes in its declaration, and each group of related functionality, or each conformance, goes in an extension of its own, often in its own file. The standard library itself is written this way. Sable's extensions are Swift's, with one addition: a syntax for extending every array of a kind at once, since an array type has no name to extend.
Extension syntax#
Write extension and the type's name, then the new members in braces:
extension String { var isBlank: Bool => trimmed().isEmpty fn repeated(_ n: Int) -> String { var result = "" for _ in 0..<n { result += self } return result }}print("ab".repeated(3))// prints abababprint(" ".isBlank)// prints trueInside an extension, self and the type's other members are available as they are in the type's own body. The new members belong to every value of the type, including values made before the extension's code was compiled; to code elsewhere they look exactly like members declared in the type.
An extension may also add a conformance to protocols, after a colon: extension Point: Equatable { … }. Members it adds are internal unless marked otherwise, like any declaration (Modules and Access Control).
Computed properties#
An extension may add computed properties, read-only or with a setter, and static ones:
extension F64 { var km: F64 => self * 1_000.0 var m: F64 => self var cm: F64 => self / 100.0}let marathon: F64 = 42.195let metres = marathon.km // 42195 metresIt can't add stored properties, or properties with field-backed accessors, since those need storage in the value (see What extensions can't add).
Methods#
Extensions add instance methods and static methods. On a value type, a method that changes self is marked mutating, as in the type's own body:
struct Point { var x: Int var y: Int}extension Point { fn distance(to other: Point) -> Int => (x - other.x).abs() + (y - other.y).abs() mutating fn moveBy(dx: Int, dy: Int) { x += dx y += dy } static fn origin() -> Point => Point { x: 0, y: 0 }}var p = Point.origin()p.moveBy(dx: 3, dy: 4)print(p.distance(to: .origin()))// prints 7Initialisers#
An extension may add initialisers, with rules that depend on the kind of type.
For a struct, enum, union or built-in type, the initialiser must give self a value on every path: a struct's field by field, or any of them by delegating with self.init(…) or by assigning self = … whole. A path that leaves a field, or self, without a value is an error (S3028), and so is reading self before it has one (S6008):
extension Point { init(both n: Int) { self.init(x: n, y: n) }}extension String { init(twice s: String) { self = s + s }}enum Light { Red, Green }extension Light { init(go: Bool) { self = go ? .Green : .Red }}let diagonal = Point(both: 5)let echo = String(twice: "ha") // "haha"Adding an initialiser in an extension doesn't remove a struct's memberwise initialiser, as declaring one in the struct's own body would. So a struct can keep Point(x:y:) and gain Point(both:) too.
For a class, an extension may add only a convenience init, which hands the work to one of the class's own initialisers with self.init(…) (S3141). It isn't inherited by subclasses. A designated initialiser — one that sets the stored properties itself — must be in the class's declaration, where the compiler can see every one of them (S3030):
class Account { var owner: String var balance: Int init(owner: String, balance: Int) { self.owner = owner self.balance = balance }}extension Account { convenience init(owner: String) { self.init(owner: owner, balance: 0) }}A protocol's extension can't add an initialiser at all; a static function that returns Self does the same job. Initialisers are covered fully in Initialization.
Subscripts#
An extension may add subscripts. This one gives every Int its decimal digits, counted from the right:
extension Int { subscript(digit index: Int) -> Int { get { var base = 1 for _ in 0..<index { base *= 10 } return (self / base) % 10 } }}let year = 2026print(year[digit: 0])// prints 6print(year[digit: 3])// prints 2Operators#
Operators are members too (Methods, Subscripts and Operators), so an extension can add them:
extension Point { operator + (a: Point, b: Point) -> Point => Point { x: a.x + b.x, y: a.y + b.y } prefix operator - (p: Point) -> Point => Point { x: -p.x, y: -p.y }}let sum = Point { x: 1, y: 2 } + Point { x: 3, y: 4 }Only the overloadable operators can be given new meanings; Sable has no custom operators.
Nested types#
An extension may declare types nested inside the type it extends:
extension Point { enum Quadrant { First, Second, Third, Fourth, OnAxis } var quadrant: Quadrant { get { if x == 0 || y == 0 { return .OnAxis } if x > 0 { return y > 0 ? .First : .Fourth } return y > 0 ? .Second : .Third } }}let q = Point { x: -2, y: 5 }.quadrantprint("\(q)")// prints SecondOutside, the nested type is Point.Quadrant.
Adding protocol conformance#
An extension can make an existing type conform to a protocol, by naming the protocol and implementing its requirements. This is retroactive conformance, and works for types you didn't declare:
protocol Describable { fn describe() -> String}extension Point: Describable { fn describe() -> String => "(\(x), \(y))"}extension Bool: Describable { fn describe() -> String => self ? "yes" : "no"}If the type already has every member the protocol requires, the extension can be empty: it only declares the conformance. Declaring it is still required, since conformance is never inferred from matching members.
A conformance must be declared in the module of the type or of the protocol, never a third (the coherence rule from Protocols).
Extending generic types#
When you extend a generic type, name its type parameters after it. They're the type's own, available throughout the extension:
struct Box<Item> { var item: Item}extension Box<T> { fn held() -> T => item fn map<U>(_ f: (T) -> U) -> Box<U> => Box<U> { item: f(item) }}Constrained extensions#
An extension may add members only for some instances of a generic type, with a where clause. Inside, the members may rely on the constraint:
extension Box<T> where T: Comparable { fn isLarger(than other: Box<T>) -> Bool => item > other.item}extension Box<T> where T == String { var shout: String => item.uppercased()}Box(item: 3).isLarger(than: Box(item: 2)) works; on a Box<any Shape> there's no isLarger at all (S3023, naming the constraint). When two members of extensions of one type fit a call equally well, the one whose extension says exactly what a parameter is (where T == F64) is chosen over one that says only what it conforms to (where T: Numeric).
A constrained extension may add a conformance too — conditional conformance, covered in Generics:
extension Box: Equatable where Item: Equatable { operator == (lhs: Box<Item>, rhs: Box<Item>) -> Bool => lhs.item == rhs.item}Extending protocols#
An extension of a protocol adds members to every type that conforms to it — current conformers and future ones. The members may use the protocol's requirements:
protocol Indexed { associatedtype Element var count: Int { get } subscript(i: Int) -> Element { get }}extension Indexed { var isEmpty: Bool => count == 0 fn first(where p: (Element) -> Bool) -> Element? { for i in 0..<count { if p(self[i]) { return self[i] } } return none }}A member that implements one of the protocol's requirements becomes that requirement's default; any other member is a helper. The two dispatch differently, as Protocols explains. A protocol extension may be constrained too, extension Indexed where Element: Equatable { … }, to give members only to conformers that meet it.
Extending arrays#
The array family — T[], T[k], T[..k], T[>..], T[>..<] and the slice T[:] (from Arrays and Collections) — has no type name to write parameters after. So an extension of every array of a kind declares its parameters after the keyword, the way a generic function does after fn:
// every grow-only array, whatever its elementextension<Element> Element[>..] { mutating fn appendTwice(_ e: Element) { append(e) append(e) }}var log: String[>..] = []log.appendTwice("tick")print(log.count)// prints 2Inside, self is the array. The parameters may be constrained, inline or with where, and the members belong to an array only where its element meets them:
extension<T: Comparable> T[:] { fn largest() -> T { var best = self[0] for candidate in self { if best < candidate { best = candidate } } return best }}print([3, 9, 4].largest())// prints 9Calling largest() on an array of a type that isn't Comparable is an error that names the constraint (S3023). An extension may also be for one element type alone, with no parameters:
extension U8[:] { fn checksum() -> Int { var sum = 0 for b in self { sum += b as Int } return sum % 256 }}These are the rules:
- Each kind is extended on its own.
T[]means every fixed-at-construction array,T[..]every inline-capacity one, andT[>..],T[>..<]andT[:]the others. No size or capacity is written:extension<T> T[8]is an error (S3083). - A slice's members are every array's. Every kind of array can be viewed as a slice, so what an extension of
T[:]declares, every kind has — which makesT[:]the usual thing to extend. Inline arrays (T[k],T[..k]) are lent to such a member where they are, so amutatingone changes the array in place. A kind's own member of the same name comes before the slice's. - More specific members come first. Of two members that fit a call equally well, one for a specific element type (
U8[:]) beats one for any element, and one whose constraints imply the other's beats that other:extension<E: SIMDScalar> E[:]beatsextension<E: Equatable> E[:], because SIMDScalar refines Comparable, which refines Equatable. An array's own member also beats a protocol extension's member that takes any sequence, soxs.append(contentsOf: ys)is the array's. - Every parameter must appear in the array type.
extension<T> Int[>..]is an error (S3083), sinceTcould never be inferred. A named generic type's parameters are written after its name, never afterextension(S3083 again). - Growable kinds may have initialisers. An extension of
T[>..]orT[>..<]may declareinits, because such an array always has a value to start from:selfbegins as[].Int[>..](repeating: 0, count: 3)calls one of the standard library's. Aninit()requirement of a protocol is met by[]unless the extension declares one. - Members are generic. They're monomorphised for each element type, like any generic code. The standard library declares the array family's own members —
count,append,contains,sortand the rest — in exactly this way.
Conformances for arrays#
An array extension may conform the arrays to protocols, and they conform wherever the element meets the extension's constraints. That's how every kind of array, and a slice, is Equatable, Hashable and Comparable (in lexicographic order) when its element is, as in Swift — so ["a", "b"] == words works, xs < ys compares arrays, and an array can be a dictionary's key:
extension<Element: Debug> Element[:]: Debug { fn debugDescription() -> String { var parts: String[>..] = [] for e in self { parts.append(e.debugDescription()) } return "[" + parts.joined(separator: ", ") + "]" }}An operator that such a conformance declares on T[:] takes arrays of any kind on either side. An array can conform only to protocols: extension<T> T[>..<]: Int is an error (S3083).
PlainData#
Some array members need elements that are nothing but their bytes — for viewing a slice of F32s as bytes, say, or handing a buffer to C. These are constrained to the standard library's PlainData protocol: extension<Element: PlainData> Element[:].
PlainData is met by the integers and floats, by structs made only of them with no padding and no deinit (and neither @noncopy nor @inline_layout), and by inline arrays T[k] of such types. A Bool, Char, enum, union, optional, tuple, class, closure, reference, or array with a heap buffer isn't plain. Like Sendable, conformance is decided by what a type is made of; a type that declares : PlainData anyway is checked against it (S3490). Inline Layout has more.
What extensions can't add#
An extension adds behaviour, not storage or a new way to build a value:
- No stored properties (S3029). The layout of a value is fixed by its declaration, which code that never sees the extension depends on. This includes
field-backed accessors, which are storage, and applies to arrays as to any type. - No designated initialisers on classes (S3030). Only
convenience inits, which delegate to the class's own. - No initialisers on protocols.
- No extensions of unnamed types other than arrays: a tuple or function type can't be extended (S3031).