DocsLanguage Guide
Enums and Unions
Named integers and flag sets, tagged unions with payloads, and structural unions.
Sable has two declarations for "one of several things", where Swift and Rust have one. An enum is a set of named integers: North, South, East and West, or HTTP status codes, or a bitset of permissions. A union is a tagged sum: a value that is one of several cases, each of which may carry values of its own, as a shape is a circle with a radius or a rectangle with a width and height.
This chapter covers both, and then a third, lighter form: structural unions such as Int | String, which need no declaration at all. Taking values apart with match is touched on here and covered fully in Pattern Matching.
Enumerations#
You introduce an enum with enum and list its cases inside braces:
enum CompassPoint { North South East West}Cases on one line are separated by commas, as members are in any one-line body:
enum Planet { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune }Each case is a value of the enum's type. You name one through the type, and once the type is known you can drop it and write only a leading dot:
var directionToHead = CompassPoint.WestdirectionToHead = .EastInterpolating or printing a case gives its name:
print("Heading \(directionToHead)")// prints Heading EastCase names are written in UpperCamelCase, like types. An enum's cases are matched with match, which must cover every case or have a default:
match directionToHead { case .North => print("Lots of planets have a north") case .South => print("Watch out for penguins") case .East => print("Where the sun rises") case .West => print("Where the skies are blue")}// prints Where the sun risesThe integer behind each case#
Unlike a Swift enum, a Sable enum always is an integer. Each case has an integer value, and the enum is laid out as that integer, which makes enums free to store and pass, and exactly what C expects of one.
The integer type is Int unless you name another after a colon:
enum Status: U8 { Pending = 0 Active = 1 Closed = 9}A case's value is what it writes after =. That may be a literal, an earlier case, or those combined with |, &, ^, +, -, *, <<, >> and ~:
enum HttpStatus: U16 { Ok = 200 Created NotFound = 404 Teapot = NotFound + 14}A case that writes no value is one more than the case before it, and the first case is 0. So HttpStatus.Created is 201, CompassPoint.North is 0 and West is 3, and in enum Planet { Mercury = 1, Venus, Earth } Earth is 3.
No two cases of an ordinary enum may have the same value (S3142): a value names exactly one case.
Converting to and from integers#
as converts in both directions:
let code = HttpStatus.Teapot as U16print(code)// prints 418let status = 404 as HttpStatusprint(status)// prints NotFoundcase as Integer is the integer the case is. integer as Enum is the case the integer is, and traps when no case has that value:
fatal error: no case of 'HttpStatus' has this valueSo convert an integer from outside your program, from a file or a network, only after checking it, or match on the integer first.
Flag Sets#
Mark an enum @flags and it becomes a set of bits, each case a flag that may be on or off independently:
@flagsenum Permissions: U32 { None = 0 Read Write Execute All = Read | Write | Execute}In a @flags enum, a case without a value takes the next bit up, starting from 1: Read is 1, Write 2 and Execute 4. Cases may share values here, since a combination like All is a case too.
A value of a flags enum is any set of its cases, not only one. You write a set as an array literal of cases, and [] for none:
let readWrite: Permissions = [.Read, .Write]let nothing: Permissions = []print(readWrite.contains(.Write))// prints trueprint(readWrite.contains([.Write, .Execute]))// prints falsecontains is true when every flag of its argument is set. The bitwise operators work as on integers: | combines sets, & keeps what two have in common, ^ keeps what only one has, and ~ flips every bit of the integer, not only the declared flags, so mask the result when you want the flags a set lacks: ~readWrite & .All is .Execute. == compares two sets.
Interpolated, a flags value is the name of the case it is exactly, or else its integer:
print(readWrite | .Execute) // prints Allprint(nothing) // prints Noneprint(readWrite) // prints 3Because a flags value may be any combination, matching on one by its cases can never be exhaustive. A match on a flags enum needs a default (S6003 without one):
match readWrite { case .Read => print("read only") case .All => print("everything") default => print("some combination")}// prints some combinationDeriving Conformances for Enums#
@derive asks the compiler to write protocol conformances for you. On an enum:
EquatableandHashablecompare and hash cases;Comparableorders cases as they are declared;Debugdescribes a case with its type,Direction.East.
@derive(Equatable, Comparable, Debug)enum Size { Small, Medium, Large }print(Size.Small < Size.Large)// prints trueprint(Size.Medium.debugDescription())// prints Size.MediumA @flags enum derives Equatable, Hashable and Debug by its integer, and describes a value as the case it is exactly, Permissions.Read, or else as Permissions(3). It is never Comparable: sets of flags have no natural order. Derivation in general, for structs and unions too, is covered in Derivation and Source Generators.
Unions#
A union is a value that is exactly one of several cases, where each case may carry a payload: values that belong to that case alone. It is the type to reach for whenever the parts a value has depend on which kind it is.
union Shape { Circle(radius: F64) Rect(width: F64, height: F64) Empty}A Shape is a circle, which has a radius; or a rectangle, which has a width and height; or empty, which has nothing. You make one by naming the case and giving its payload like a call:
let wheel = Shape.Circle(radius: 2.0)let door: Shape = .Rect(width: 3, height: 4) // leading-dot inferenceA payload's values may be labelled, as above, or not:
union Barcode { Upc(Int, Int, Int, Int) QrCode(String)}var productBarcode = Barcode.Upc(8, 85909, 51226, 3)productBarcode = .QrCode("ABCDEFGHIJKLMNOP")Labels are worth writing when the payload's meaning isn't obvious from its type: Rect(width: 3, height: 4) says which is which, Upc(8, 85909, 51226, 3) doesn't.
Reading the payload#
You get at a payload by matching, binding each value with let:
match productBarcode { case .Upc(let system, let manufacturer, let product, let check) => print("UPC: \(system), \(manufacturer), \(product), \(check)") case .QrCode(let code) => print("QR code: \(code)")}// prints QR code: ABCDEFGHIJKLMNOPLabelled payload values can be matched by label, case .Rect(width: let w, _). Pattern Matching has every form.
Members of unions#
Unions may have methods, computed properties, static members and protocol conformances, exactly like structs:
union Shape { Circle(radius: F64) Rect(width: F64, height: F64) Empty static let unit: Shape = .Rect(width: 1, height: 1) var area: F64 => match self { case .Circle(let r) => 3.14159 * r * r case .Rect(let w, let h) => w * h case .Empty => 0.0 } fn scaled(by k: F64) -> Shape { return match self { case .Circle(let r) => .Circle(radius: r * k) case .Rect(let w, let h) => .Rect(width: w * k, height: h * k) case .Empty => .Empty } }}print(Shape.unit.scaled(by: 2).area)// prints 4.0A mutating method changes a union's case by assigning to self, as shown in Methods. Printed, a union value describes its case and payload: Shape.Rect(width: 2.0, height: 2.0).
Generic unions#
A union may have type parameters. The standard library's Outcome, Sable's equivalent of Swift's and Rust's Result, is a union declared like this:
public union Outcome<T, E> { Ok(T) Err(E) fn map<U>(_ f: (T) -> U) -> Outcome<U, E> { return match self { case .Ok(let v) => .Ok(f(v)) case .Err(let e) => .Err(e) } }}fn half(_ n: Int) -> Outcome<Int, String> { return n % 2 == 0 ? .Ok(n / 2) : .Err("\(n) is odd")}Generic types are the subject of Generics.
Recursive unions#
A union may contain itself. An arithmetic expression is a number, or the sum of two expressions, or their product:
union ArithmeticExpression { Number(Int) Addition(ArithmeticExpression, ArithmeticExpression) Multiplication(ArithmeticExpression, ArithmeticExpression)}fn evaluate(_ expression: ArithmeticExpression) -> Int { return match expression { case .Number(let value) => value case .Addition(let left, let right) => evaluate(left) + evaluate(right) case .Multiplication(let left, let right) => evaluate(left) * evaluate(right) }}// (5 + 4) * 2let five = ArithmeticExpression.Number(5)let sum = ArithmeticExpression.Addition(five, .Number(4))let product = ArithmeticExpression.Multiplication(sum, .Number(2))print(evaluate(product))// prints 18A value can't hold a copy of its own type inline, or it would be infinitely large. Swift makes you mark such cases indirect; Sable notices the recursion and boxes the recursive case automatically, putting its payload in a reference-counted heap allocation. You can force boxing with @indirect, on a single case or on the whole union, when you want a large payload kept out of line even though it isn't recursive:
@indirectunion Path { Start Then(Path, Move)}Optional Is a Union#
Optionals, from The Basics, are no special machinery. Optional<T>, written T?, is a frozen union of two cases, in effect:
@frozen union Optional<T> { Some(T), None }So .Some(x) and .None are values you can write, and the cases you match. The literal none is shorthand for .None, and is the idiomatic spelling; a plain x where a T? is expected becomes .Some(x) for you.
let maybe: Int? = .Some(3)let missing: Int? = noneOptionals covers the syntax built on top: binding, chaining, ?? and the rest.
Frozen Unions and Other Modules#
A match must be exhaustive. Within its own module, a union's cases are all known, so matching every case is enough. But a library may add a case to a public union in a later version, and code in another module that matched every case would then break.
So a public union matched from another module needs a default, unless the union is marked @frozen. @frozen is a promise that the union will never gain a case, as Optional never will, and lets other modules match it exhaustively without one:
@frozenpublic union Signal { Red, Amber, Green }Enums are different: their values are integers, and a match on one already needs every case or a default.
Variant-Sized Unions#
An ordinary union is as large as its largest case, so that any value of it can be any case. A variant-sized union, declared with .. after its name, makes each value exactly the size of its own case:
public union Node.. { Leaf(value: I32) Branch(left: Node&<u32>, right: Node&<u32>)}The values pack tightly, one after another, which suits trees and messages laid out in a buffer. In exchange, an existing value can't change its case. Variant-sized unions belong to Sable's inline layouts, covered in Inline Layout.
Structural Unions#
Sometimes you want "an Int or a String" without declaring a union for it. A structural union is written with | between types:
fn describe(_ value: Int | String | Bool) -> String { if value is Int { return "the number \(value + 1)" } // value is an Int here if value is String { return "\(value.count) characters" } // a String here return "the flag \(value)" // so a Bool here}print(describe(41))// prints the number 42print(describe("abc"))// prints 3 charactersA value of any member type converts to the union implicitly. Reading it as one of its types relies on flow-sensitive narrowing: after value is Int succeeds, value is an Int in that branch, and after the if returns, the compiler knows it isn't one below. is, match and if let all narrow, as != none narrows an optional. In a match, case let n as Int binds the value as that type:
fn show(_ v: Int | String) -> String { return match v { case let n as Int => "number \(n)" case let s as String => "text \(s)" }}Structural unions are compared by their member types, not by name: Int | String and String | Int are the same type, and nested ones flatten, so (A | B) | C is A | B | C. They must be bounded, with every member type known when compiling, so a structural union can't contain an any P existential; that is what keeps a match on one checkable for exhaustiveness. Under the hood, each distinct set of types is lowered to one ordinary tagged union.
They suit types like JSON, whose shape is a fixed set of alternatives:
alias Json = Null | Bool | F64 | String | Json[] | [String: Json]Why Enums and Unions Are Separate#
Swift and Rust have one enum that covers both named integers and tagged sums. Sable keeps them apart deliberately. An enum is a named integer: it has the C ABI of an integer, converts to and from one with as, and can be a bitset with @flags. A union is a tagged sum, whose layout is the compiler's to choose. Folding both into one declaration makes both stories worse: "is this C-compatible?" and "just give me a bitfield" turn into questions about which features you avoided.
Separating them also leaves the compiler free to lay unions out compactly. It puts a union's tag in bits its payloads never use, so a T? for a class T is one pointer, with none as null. A union with one payload case and several empty ones, like Optional, uses the payload's invalid values for the empty cases, so Outcome<T, Never> is exactly the size of a T. And it boxes recursive cases, as described above. You get those layouts without asking for them.