DocsLanguage Guide
Protocols
Requirements, associated types, default implementations, some and any, and composition.
A protocol describes what a type can do — the methods, properties, initialisers and other members it must have — without saying how. A struct, class, union or enum conforms to a protocol by providing those members, and code written against the protocol then works with every conforming type.
Sable's protocols are close to Swift's: requirements, associated types, default implementations, some and any. Two things are stricter than Swift's: conformance is always declared, never inferred from matching members, and each conformance may be declared in only one place, so it is unique across a whole program.
Protocol syntax#
A protocol lists its requirements in a body, like a type's, but with no implementations:
protocol Shape { var name: String { get } fn area() -> F64 fn perimeter() -> F64}A type conforms by naming the protocol after a colon, as a class names its superclass, and implementing every requirement. Several protocols are separated by commas:
struct Circle: Shape { var radius: F64 var name: String { get => "circle" } fn area() -> F64 => 3.14159 * radius * radius fn perimeter() -> F64 => 2.0 * 3.14159 * radius}struct Square: Shape, Equatable { var side: F64 var name: String { get => "square" } fn area() -> F64 => side * side fn perimeter() -> F64 => 4.0 * side operator == (lhs: Square, rhs: Square) -> Bool => lhs.side == rhs.side}A class names its superclass first, then its protocols.
Conformance is nominal and explicit. A type that happens to have an area() and a perimeter() is not a Shape until it says so. A type that says so but leaves out a requirement is an error that names each missing member (S3023), and one whose member has the wrong signature — fn area() -> Int, say — is S3027.
Property requirements#
A property requirement gives the property's name and type, and says whether it must be readable ({ get }) or readable and writable ({ get set }). It doesn't say whether the property is stored or computed; the conformer chooses:
protocol Named { var name: String { get }}protocol Labelled { var label: String { get set }}struct Person: Named, Labelled { var name: String // a stored property meets '{ get }' var label: String // and a 'var' meets '{ get set }'}struct Planet: Named { var index: Int var name: String => index == 3 ? "Earth" : "planet \(index)" // computed}A { get } requirement may be met by a constant, a variable, or a computed property; a { get set } requirement needs a settable one, so a get-only computed property doesn't meet it (S3027).
Method requirements#
A method requirement is the method's signature. Methods that change a value type's self are marked mutating in the requirement, which lets a struct meet it with a mutating method (a class's methods may always change the object):
protocol Counter { var count: Int { get } mutating fn increment()}struct Clicks: Counter { var count: Int = 0 mutating fn increment() { count += 1 }}A requirement may be an operator, as Equatable's == is. The built-in numbers meet the numeric protocols' operators already; a type of your own writes them:
protocol Summable { operator + (lhs: Self, rhs: Self) -> Self}struct Money: Summable { var cents: Int operator + (lhs: Money, rhs: Money) -> Money => Money { cents: lhs.cents + rhs.cents }}A requirement may also be generic, fn visit<T: Named>(_ item: T), async, and throw.
Static requirements#
Mark a requirement static to require a member of the type rather than of its values. A conformer must meet it with a static member; an instance method of the same name doesn't count (S3027):
protocol Defaulted { static fn makeDefault() -> Self}struct Settings: Defaulted { var verbose: Bool static fn makeDefault() -> Settings => Settings { verbose: false }}Initialiser requirements#
A protocol may require an initialiser, so that generic code can make values of the conforming type. A requirement may throw, and it is met by an initialiser that throws the same error type, or nothing at all:
protocol Parsable { init(parsing text: String) throws(ParseError)}struct Version: Parsable { var major: Int init(parsing text: String) throws(ParseError) { guard let n = text.toInt() else { throw .BadDigit(at: 0) } major = n }}The standard library's FromSequence works this way: its requirement init<S: Sequence>(_ elements: S) is what lets collect() build any collection.
Subscript requirements#
A subscript requirement gives the parameters and element type, and { get } or { get set }:
protocol Grid { associatedtype Cell subscript(x: Int, y: Int) -> Cell { get }}Default implementations#
A protocol may give a requirement a body. That body is the default implementation: a conformer that doesn't write the member gets it, and one that does write it replaces it.
protocol Shape { var name: String { get } fn area() -> F64 fn describe() -> String { return "a \(name) of area \(area())" }}Defaults may also be added afterwards, in an extension of the protocol, along with members that are no requirement at all — helpers built on the requirements, which every conformer gets:
extension Shape { fn isLarger(than other: some Shape) -> Bool => area() > other.area()}Extensions are covered in Extensions. There is one important difference between the two kinds of member, which comes from how calls are dispatched:
- A requirement is called through the conformance, so the conformer's own implementation runs, even from generic code or through an
any Shape. - A member of an extension that is not a requirement is chosen by the static type of the expression. A conformer that writes a method of the same name doesn't replace it for callers that see only the protocol.
This is Swift's model. Since it can surprise, the compiler warns when an extension member shadows a requirement-like name in a way that will behave like this. If you want conformers to be able to replace a member, make it a requirement with a default.
Protocol inheritance#
A protocol may refine other protocols, adding requirements to theirs. Conforming to it means meeting all of them:
protocol Drawable { fn draw() -> String}protocol Sprite: Drawable { var position: (Int, Int) { get }}A Sprite must implement draw() and position, and any Sprite can be used where a Drawable is wanted. The standard library's protocols refine each other in this way: Comparable refines Equatable, Hashable refines Equatable, and Error refines Debug and Sendable.
Associated types#
A protocol sometimes needs to talk about a type that each conformer chooses: the element of a collection, the cell of a grid. An associated type is a placeholder for that type, declared with associatedtype:
protocol Container { associatedtype Item fn count() -> Int fn at(_ index: Int) -> Item}A conformer says what Item is with an alias, or leaves it to be inferred from its members:
struct Numbers: Container { alias Item = Int var values: Int[>..] fn count() -> Int => values.count fn at(_ index: Int) -> Int => values[index]}struct Words: Container { // 'at' gives a String, so Item is String var values: String[>..] fn count() -> Int => values.count fn at(_ index: Int) -> String => values[index]}A generic conformer may set it to one of its own parameters, alias Item = T. In generic code the associated type is written after the type parameter, C.Item, and is checked like any type:
fn firstItem<C: Container>(_ c: C) -> C.Item { return c.at(0)}let n: Int = firstItem(Numbers { values: [4, 5] })Defaults and constraints#
An associated type may be constrained to protocols, like a type parameter, and may have a default that a conformer gets if it says nothing:
protocol Collection { associatedtype Element associatedtype Index: Comparable = Int var count: Int { get } subscript(i: Index) -> Element { get }}An associated type may also carry a where clause, which holds of every conformer and wherever the protocol is used as a constraint. This is how the standard library's Sequence ties its iterator's elements to its own:
protocol Sequence { associatedtype Element associatedtype Iter: Iterator where Iter.Element == Element fn makeIterator() -> Iter}Because the where clause is the protocol's, generic code over any S: Sequence may rely on S.Iter.Element being S.Element, and a conformer that names only its iterator gets its Element from that iterator. Constraints may be recursive (an associated type that is itself the same protocol, as a collection's slice is); a genuinely circular one is an error rather than a hang.
Self requirements#
Inside a protocol, Self is the conforming type. A requirement that takes or returns Self is met by a member that takes or returns the conformer's own type:
protocol Scalable { fn scaled(by factor: F64) -> Self}struct Circle: Scalable { var radius: F64 fn scaled(by factor: F64) -> Circle => Circle { radius: radius * factor }}Equatable's operator == (lhs: Self, rhs: Self) is a Self requirement: a type is compared only with values of its own type.
Adding conformance with an extension#
A type can be made to conform to a protocol after it's declared, in an extension. This works for types you didn't write, including the built-in ones — called retroactive conformance:
extension Int: Named { var name: String => "the number \(self)"}let seven = 7print(seven.name)// prints the number 7Coherence#
A given type may conform to a given protocol only once, anywhere in a program. Sable enforces this with a rule taken from Rust: a conformance T: P may be declared only in the module that declares T, or in the module that declares P — never in a third.
// in your module, with Point from a library and Serializable from another:extension Point: Serializable { } // error: neither type nor protocol is yoursSo two libraries can never both make Point conform to Serializable in different ways. That is what makes any Serializable sound, and lets a conformance be looked up in a static table. When you need a conformance neither side provides, wrap the type in one of your own:
struct SerializablePoint: Serializable { let inner: Point // ...}Explicit protocol implementation#
Two protocols may require members with the same name and parameters but different results. A type that conforms to both implements each one separately, prefixing the member's name with its protocol, as C# does:
struct Image { }struct Page { }protocol Displayable { fn render() -> Image }protocol Printable { fn render() -> Page }class Report: Displayable, Printable { fn Displayable.render() -> Image { return Image() } fn Printable.render() -> Page { return Page() }}A call through some Displayable or any Displayable gets the first; through Printable, the second.
Protocols as types: some and any#
A protocol can be used in a type in two ways, which have different costs and different powers.
Opaque types: some P#
some P means "one particular type that conforms to P, which the compiler knows and the reader doesn't need to":
fn makeShape() -> some Shape { return Circle(radius: 1)}The concrete type is fixed by the function's body and hidden from its callers. Callers can use only what Shape offers, but the compiler knows the real type, so calls are direct and can be inlined: some is an abstraction barrier, not an indirection. Every return in the function must give the same type, and two calls of it give the same type.
In parameter position, some P is shorthand for a generic parameter: fn draw(_ d: some Drawable) means fn draw<D: Drawable>(_ d: D). Generics covers this.
Existentials: any P#
any P means "a value of any type that conforms to P, which may differ from value to value". It's how you store different conformers together:
let shapes: (any Shape)[] = [Circle(radius: 1), Square(side: 2)]for shape in shapes { print(shape.name)}An any P holds its value in a box on the heap, together with the value's type metadata and, for each protocol it names, the witness table of that type's conformance — the table of the type's implementations of the requirements. That's three words for any P, and one more word for each extra protocol in any A & B. A requirement is called through the table.
Copying an any P shares the box, so copies are cheap. Changing the value through one (with a setter or a mutating requirement) first copies the box if another any P shares it, so existentials keep value semantics. Note the parentheses in (any Shape)[]: some and any take the whole type after them, so any Shape[] would be "any Shape[]".
Use some where one type will do, and any when you need values of different types in one place. A function taking some P is compiled for each type it's called with; one taking any P has one copy of the code, which makes calls through a table.
Opening an existential#
Some requirements can't be called on an any P directly. A requirement whose parameter is Self — fn same(_ other: Self) -> Bool — would need both values to be the same type, and two existentials may hold two types.
Such members become usable when the existential is opened: the value is used as its own concrete type, known from its metadata. Sable opens an existential implicitly in two places:
- when you call a member of an extension of
Pthat isn't a requirement, and - when you pass it to a generic function for a type parameter,
fn twice<T: Shape>(_ x: T)called with anany Shape.
Inside, the value's type is a type parameter like any other, so x.same(x) works. A result of that type is boxed back into an any P. Calling a requirement through an any P opens it too: a result of Self comes back as any P, and a result of an associated type as the existential of that associated type's protocols. A requirement whose result mentions Self in another shape ((Self, Int), Self??) can't be called that way (S3161). Casting, Metatypes and Reflection has the full rules.
Primary associated types#
After some, a protocol's associated types may be given in angle brackets, in the order the protocol declares them. some Sequence<Int> is a sequence whose Element is Int, which its users may rely on:
fn total(_ values: some Sequence<Int>) -> Int { var sum = 0 for v in values { sum += v } return sum}fn evens(upTo n: Int) -> some Sequence<Int> { for i in 0...n where i % 2 == 0 { yield i }}print(total(evens(upTo: 10)))// prints 30An associated type with a default that's left out is that default: Sequence's second, Failure, defaults to Never, so some Sequence<Int> can't fail and some Sequence<Int, IoError> may throw IoError (see Error Handling).
Generic protocols#
A protocol may also have type parameters of its own, in angle brackets after its name. Unlike an associated type, which each conformer chooses once, a type parameter lets one type conform to several instances of the protocol:
protocol Provides<Service> { fn provide(_ type: Service.Type) -> Service}class Answers: Provides<Int>, Provides<String> { fn provide(_ type: Int.Type) -> Int { return 42 } fn provide(_ type: String.Type) -> String { return "forty-two" }}A generic protocol's parameters are invariant unless declared out (only produced, never taken) or in (only taken). That variance makes any Producer<Dog> usable as an any Producer<Animal>; Generics explains it.
Protocol composition#
P & Q is a type that conforms to both protocols. It's written wherever a protocol could be, without declaring a new protocol for the combination:
fn store(_ key: some Hashable & Debug) { print("storing \(key.debugDescription()) at \(key.hashValue)")}alias Entity = any Named & HashableA composition may combine any number of protocols. As an existential, any A & B carries one witness table per protocol.
Protocols the language knows#
Most protocols are ordinary library declarations. A few are ones the compiler relies on to give syntax its meaning:
| Protocol | What uses it |
|---|---|
Equatable |
== and != |
Comparable |
<, <=, >, >=, and sorting |
Hashable |
dictionary keys and sets |
Sequence, Iterator |
for x in s: s.makeIterator(), then next() until none |
AsyncSequence, AsyncIterator |
for await x in s |
Error |
what throws without a type throws: any Error |
From<E> |
converting an error at a try |
Formattable |
string interpolation "\(x)" and its format specs |
Debug |
debugDescription(); interpolation of a type that isn't Formattable |
Sendable |
values that may cross between tasks and actors |
Arrays and ranges are known to for by sight; any other type is iterated through Sequence. A sequence whose Failure isn't Never is looped with for try.
Equatable, Hashable, Comparable and Debug can be written for you with @derive(...) (Derivation and Source Generators), and every array and optional is Equatable, Hashable and Comparable when its elements are.
Sendable and PlainData are structural: a type conforms by what it's made of, not by declaring anything. A struct whose fields are all Sendable is Sendable; a type that does declare : Sendable is checked, and one holding a mutable class is an error (S3410). Concurrency covers Sendable, and Inline Layout PlainData.
There are no literal protocols, as Swift's ExpressibleByIntegerLiteral is: a literal takes its type from context alone. And there's no CustomStringConvertible: interpolation uses Formattable, then Debug, then a reflected description.