DocsLanguage Reference
Declarations
Every declaration and every modifier that may be written on one.
A declaration introduces a name: a module, a constant or variable, a function, a type, a member of a type, an extension or an alias. Every declaration may be preceded by attributes (see Attributes) and modifiers. This chapter lists every declaration and every modifier, with what each permits.
The guide teaches these in Functions, Structures and Classes, Properties, Methods, Subscripts and Operators, Initialization and Deinitialization, Enums and Unions, Protocols, Generics, Extensions and Modules and Access Control.
Declaration = { Attribute } { Modifier } DeclarationKind ;DeclarationKind = FunctionDecl | StructDecl | ClassDecl | ActorDecl | ProtocolDecl | UnionDecl | EnumDecl | ExtensionDecl | AliasDecl | VariableDecl | ConstDecl | InitDecl | DeinitDecl | PropertyDecl | SubscriptDecl | OperatorDecl ;Modules and imports#
CompilationUnit = [ ShebangLine ] ModuleDecl { ImportDecl } { TopLevelDecl } EOF ;ModuleDecl = { Attribute } "module" QualifiedName NL ;ImportDecl = [ "public" ] "import" ImportTarget NL ;ImportTarget = QualifiedName [ "as" Identifier ] | QualifiedName "." "{" ImportItem { "," ImportItem } "}" | QualifiedName "." "{" "*" "}" ;ImportItem = Identifier [ "as" Identifier ] ;TopLevelDecl = Declaration | ComptimeBlock | ConditionalCompilation ;Every file begins (after an optional shebang) with one module declaration, naming the module the file belongs to. Module names are dotted; the root segment is the package's name. A module may span many files, with no correspondence between file and type names. Imports come next, then declarations.
module App.Renderingimport Sable.Collectionsimport Sable.Math as M // the module under another nameimport Sable.IO.{ File, Directory } // chosen itemsimport Sable.Core.{ Platform, Reflect as Reflection } // an item renamedimport Sable.Text.{ * } // every public item; discouraged outside a preludepublic import Sable.Math.Vectors // re-exported to this module's importers- The wildcard is braced,
{ * }, so that the line cannot end on*. public importre-exports: consumers of this module see the imported one too.- Circular dependencies between modules are an error; between files of one module, they are fine.
- An imported name is preferred over a Sable.Core name of the same spelling.
Modifiers#
Modifier = Visibility | "static" | "open" | "sealed" | "abstract" | "final" | "override" | "required" | "convenience" | "mutating" | "nonmutating" | "lazy" | "async" | "const" | "nonisolated" | "unsafe" | "weak" | "unowned" [ "(" ( "safe" | "unsafe" ) ")" ] ;Visibility = "public" | "package" | "internal" | "private" | "private" "(" "set" ")" ;| Modifier | On | Meaning |
|---|---|---|
public |
any | Visible to every consumer of the package |
package |
any | Visible within the workspace (all packages that are members of it) |
internal |
any | Visible within the module — the default |
private |
any | Visible within the enclosing declaration, and its extensions in the same module |
private(set) |
var |
Readable at the property's own visibility, settable only privately |
static |
members, module-level let/var |
Belongs to the type, not an instance; at module level, a global set once before main |
open |
class, method, property | May be subclassed or overridden outside the module; members are non-virtual without it |
sealed |
class | May not be subclassed further |
abstract |
class, member | A class that cannot be instantiated; a member subclasses must implement |
final |
class, member | May not be subclassed, or overridden |
override |
member | Overrides a superclass member; mandatory when overriding |
required |
init |
Every subclass must implement this initialiser |
convenience |
init |
Delegates to another initialiser with self.init(…) (S3141) |
mutating |
method, accessor, operator | May change self; required to do so in a struct or union |
nonmutating |
method | Accepted by the parser; has no effect today |
lazy |
var |
Computed from its initialiser on first read |
async |
fn, init, let |
An async function; with let, a child task (async let) |
const |
fn, init |
Callable at compile time |
nonisolated |
actor member | Callable without awaiting the actor |
unsafe |
fn, init |
Safe only if the caller keeps a promise; callable only in unsafe code |
weak |
var of class type |
Does not keep the object alive; optional, becomes none |
unowned, unowned(safe) |
let/var of class type |
Does not keep the object alive; traps if read after it is gone |
unowned(unsafe) |
let/var of class type |
As unowned, with no check |
unsafe is a modifier only before fn, init or another modifier (unsafe static fn, unsafe mutating fn); before a brace it begins an unsafe block. Only a function can be unsafe (S3471).
Constants and variables#
VariableDecl = [ "async" ] [ "using" ] ( "let" | "var" ) BindingPattern [ ":" Type ] [ "=" Expression ] [ Accessors ] [ "," | ";" ] NL ;TerseFieldDecl = Identifier ":" Type [ "=" Expression ] [ Accessors ] [ "," | ";" ] NL ; (* inside a type body only; declares an immutable field *)ConstDecl = "const" Identifier [ ":" Type ] "=" Expression NL ;let and var declare bindings in a body (see Statements), globals at module level, and stored properties in a type body. Inside a type body a field may be written without let: name: Type declares an immutable stored field.
struct Vec3 { x: F32, y: F32, z: F32 } // three immutable fieldsstruct Counter { var count = 0 // mutable let id: UUID // immutable}Members on one line are separated by , or ;; members on their own lines need no separator.
Constants#
const declares a compile-time constant: its value is computed while compiling and written as a literal wherever it is read. Its type may be left out when its value is a literal, another constant, a call or arithmetic on those. Whatever the value calls must be a const fn, a const init, a compiler-written initialiser, or a pure member of Sable.Core (S3220). A trap while computing it is a compile-time error (S3201 for arithmetic, S3221 otherwise). See Compile-Time Evaluation.
const maxPacket = 1500const table = buildCrcTable()Functions#
FunctionDecl = "fn" FunctionName [ GenericParams ] "(" [ ParamList ] ")" [ EffectSpec ] [ "->" ReturnType ] [ WhereClause ] FunctionBody ;FunctionName = Identifier | QualifiedName ; (* QualifiedName: explicit protocol implementation, e.g. fn Drawable.render *)FunctionBody = Block | "=>" Expression NL | NL ; (* no body: protocol / abstract *)EffectSpec = { "async" | ThrowsSpec } ;ThrowsSpec = "throws" [ "(" Type ")" ] | "rethrows" ;ReturnType = Type ; (* "-> Node&" returns a reference *)fn add(_ a: Int, _ b: Int) -> Int { return a + b }fn greet(name: String) { print("hello, \(name)") } // returns Voidfn double(_ x: Int) -> Int => x * 2 // expression bodyfn divmod(_ a: Int, _ b: Int) -> (q: Int, r: Int) { return (q: a / b, r: a % b) }async fn fetch(_ url: Url) throws(HttpError) -> Response { }- Result. Without
-> T, a function returnsVoid. A result type is always written, except that an=>body's may be inferred for a non-public function.-> Nevermeans it does not return.-> T&returns a reference rooted in a parameter, by root inference. - Body. A block,
=> expression, or none — for a protocol requirement, anabstractmember, or an@externfunction. - Effects.
asyncmakes it async: its callersawaitit.throws(E)says it may throwE; barethrowsisthrows(any Error).rethrowsthrows only when a closure argument does;rethrows(E)throwsEas well. Effects are part of the function's type:async (…) throws(E) -> T.asyncmay be written beforefnas a modifier or after the parameters. - Explicit protocol implementation.
fn Drawable.render() -> ImageimplementsrenderforDrawablealone, when two protocols require members of the same name. - Overloading on parameter types, counts and labels is allowed; on the result type alone it is not.
- Local functions may be declared in a body; see Statements.
const fnmay be called at compile time; its body may allocate, loop and call otherconst fns, but not do I/O orunsafework.unsafe fnmay be called, or taken as a value, only in anunsafeblock or anotherunsafe fn(S3470).
Parameters#
ParamList = Param { "," Param } [ "," ] ;Param = { Attribute } [ ParamModifier ] [ ParamLabel ] Identifier ":" [ ParamModifier ] Type [ "..." ] [ "=" Expression ] ; (* the modifier may precede the name or follow the colon; the second form composes with an external label. 'in name:' is the label 'in', not the modifier: 'fn build(in r: region)' is called 'build(in: a)' *)ParamModifier = "inout" | "out" | "consuming" | "in" ; (* a parameter that refers to its argument says so in its type, "a: Node&"; "ref" and "borrowing" are reserved, and an error (S1013) *)ParamLabel = Identifier | Keyword | "_" ; (* external label *)fn relocate(from source: Point, to destination: Point) { }fn insert(_ item: Element, at index: Int) { }fn connect(host: String, port: Int = 443, timeout: Duration = .seconds(30)) { }fn sum(of values: Int...) -> Int { }fn tryParse(_ s: String, out value: Int) -> Bool { }fn scale(_ v: inout Vec3, by factor: F32) { }fn store(_ handle: consuming FileHandle) { }fn area(_ r: Rect&) -> F64 { }- Labels. A parameter may have an external label before its name;
_means none. A parameter with a single name is called with that label or without it. A label may be a keyword:fn first(where predicate: (Element) -> Bool). - Defaults.
= expressionis evaluated at each call that leaves the argument off, in the declaration's scope; its generic parameters are what that call gives them. A default of#file,#line,#columnor#functiontakes the call's place;#expressionis described in Lexical Structure. - Variadic.
T...takes any number ofTs, written as separate arguments. - Ownership. The modifier is written before the name or after the colon; the second form reads better with a label,
fn read(into buffer: inout U8[]).
| Parameter | The callee gets | The caller writes |
|---|---|---|
x: T |
A copy (a class or @noncopy value is passed by reference) |
f(x) |
x: T& |
The caller's value, read in place | f(x) |
x: inout T |
Exclusive access to the caller's variable, changed in place | f(&x) |
x: out T |
The caller's variable, which it must assign before returning | f(&x) or f(out x) |
x: consuming T |
Ownership of the value | f(x) or f(move x) |
ref and borrowing are not Sable (S1013): a parameter that refers to its argument says so in its type, T&. An inout, out or & argument must name a place an assignment could write.
- Attributes on a parameter's type.
@escaping,@autoclosureand@Sendableare written on the type,f: @escaping () -> Int; before the parameter they are S1014. See Attributes. - Region parameters.
fn build(in r: region) -> Node&takes the region to allocate in.inthere is the external label, not a modifier.
Generators#
A function, method, computed property or closure whose result is some Sequence<T> or some Iterator<T> (some AsyncSequence<T> or some AsyncIterator<T> for an async one) and whose body contains yield is a generator.
fn evens(upTo n: Int) -> some Sequence<Int> { var i = 0 while i <= n { yield i i += 2 }}- Calling it runs nothing: it captures its arguments (and
self) by value, and the body runs a step at a time asnext()asks. EachmakeIterator()starts afresh; a copy of an iterator goes on independently. returnwith no value, or the end of the body, finishes it;returnwith a value is S3482. Aninoutoroutparameter is S3483.- A generator declared
throws(E)gives a sequence whoseFailureisE, so it is iterated withfor try; the call itself throws nothing. Once it has thrown, it is finished. - Its pending
defers run when it finishes or when its iterator is dropped; adeferbody may notyield(S3481). yieldelsewhere is S3480, as is a result that names no sequence of what is yielded.
Generic parameters and where clauses#
GenericParams = "<" GenericParam { "," GenericParam } ">" ;GenericParam = { Attribute } [ "out" | "in" ] Identifier [ ":" TypeList ] [ "=" Type ] ; (* "N: Int", an integer type: a value parameter *)WhereClause = "where" WhereItem { "," WhereItem } ;WhereItem = Type ":" TypeList (* conformance / inheritance *) | Type "==" Type (* same-type constraint *) | Expression ; (* const generic predicate *)TypeList = ConstraintType { "&" ConstraintType } ; (* composition in constraints *)ConstraintType = [ "~" ] Type ; (* "~Copyable" lifts the implicit constraint *)Functions, initialisers, subscripts, structs, classes, actors, protocols, unions and aliases may be generic.
fn max<T: Comparable>(_ a: T, _ b: T) -> T => a >= b ? a : bstruct Cache<Key: Hashable, Value> { private var items: [Key: Value] = [:]}fn zip<A, B, S1, S2>(_ a: S1, _ b: S2) -> some Sequence<(A, B)> where S1: Sequence<A>, S2: Sequence<B>, A: Sendable { }struct Ring<T, N: Int> where N > 0 { var slots: T[N] }struct Box<T: ~Copyable> { private var value: T }protocol Producer<out T> { fn next() -> T? }protocol Consumer<in T> { fn accept(_ value: T) }| Constraint | Meaning |
|---|---|
T: P |
Conforms to protocol P (P & Q for several) |
T: Widget |
Is or inherits from class Widget |
where S.Element == T |
Same-type |
T: Sendable |
Safe to cross an isolation boundary |
T: ~Copyable |
May be a move-only type (lifts the implicit Copyable) |
N: Int |
A value parameter: a number, not a type |
where N > 0 |
A predicate over value parameters, checked per instance (S3421) |
where Self: P |
On a method: asked of each call, known in the body |
- Generic code is monomorphised: each instantiation is compiled for its types.
@polymorphicopts a function into one boxed copy. outandinon a protocol's parameter declare it covariant or contravariant, which makes its existentials variant; a parameter in the wrong position is S3047. Generic types are otherwise invariant.- A parameter may have a default type,
= Type. Sized(statically known size) appears in the spec as a constraint but has no compiler handling yet.
Structures#
StructDecl = "struct" Identifier [ GenericParams ] [ ":" TypeList ] [ WhereClause ] TypeBody ;TypeBody = "{" { MemberDecl } "}" ;MemberDecl = Declaration | TerseFieldDecl | AssociatedTypeDecl | ConditionalCompilation ;A struct is a value type: assigning or passing one copies it (copy-on-write for the buffers inside). It may have stored and computed properties, methods, initialisers, subscripts, operators, static members and nested types, conform to protocols and be generic.
struct Vec3 { var x: F32 var y: F32 var z: F32 static let zero = Vec3(x: 0, y: 0, z: 0) var length: F32 => (x * x + y * y + z * z).sqrt() mutating fn scale(by f: F32) { x *= f; y *= f; z *= f } operator + (a: Vec3, b: Vec3) -> Vec3 => Vec3(x: a.x + b.x, y: a.y + b.y, z: a.z + b.z)}- A struct that declares no
inithas a memberwise initialiser,Vec3(x:y:z:), whose parameters for fields with initial values have those defaults. It may also be made with a record literal,Vec3 { x: 1, y: 2, z: 3 }. - A method that changes
selfmust bemutating. - A
@noncopy structis move-only and may declare adeinit.
Classes#
ClassDecl = "class" Identifier [ GenericParams ] [ ":" TypeList ] [ WhereClause ] TypeBody ;A class is a reference type with identity, reference-counted. The first type in its list may be its superclass; the rest are protocols. Single inheritance, many conformances.
public open class Document: Serializable { public var title: String public weak var owner: Workspace? public unowned let store: Store public init(title: String, store: Store) { self.title = title self.store = store } deinit { store.unregister(self) } public open fn render() -> String { return title } public override fn description() -> String => "Document(\(title))"}- Members are non-virtual unless
openorabstract;overrideis mandatory when overriding;finalstops further overriding. - A class is subclassable outside its module only if
open;sealedstops all further subclassing;abstractmakes it uninstantiable. - A class with no
initwhose stored fields all have initial values is made withinit(); a subclass with noinitinherits its superclass's initialisers. ===and!==compare identity.
Actors#
ActorDecl = "actor" Identifier [ GenericParams ] [ ":" TypeList ] [ WhereClause ] TypeBody ;An actor is a reference type whose state is isolated: it runs one call at a time. A call into it or a read of its state from outside is awaited; a call it makes to itself is not. A nonisolated member is reached without awaiting — an immutable let, or a method that touches no isolated state. An isolated method meets a protocol's async requirement but not a synchronous one (S3237). Actors are reentrant at each await.
actor Counter { private var value = 0 fn increment() { value += 1 } nonisolated let id: UUID}Protocols#
ProtocolDecl = "protocol" Identifier [ GenericParams ] [ ":" TypeList ] [ WhereClause ] ProtocolBody ;ProtocolBody = "{" { ProtocolMember } "}" ;ProtocolMember = { Attribute } { Modifier } ( AssociatedTypeDecl | FunctionDecl (* body optional = default impl *) | PropertyDecl | SubscriptDecl | InitDecl | OperatorDecl ) ;AssociatedTypeDecl = "associatedtype" Identifier [ ":" TypeList ] [ "=" Type ] [ WhereClause ] NL ; (* the where clause is the protocol's: "where Iter.Element == Element" *)A protocol declares requirements: methods, properties (with { get } or { get set }), subscripts, initialisers, operators and associated types. A requirement given a body has a default implementation.
public protocol Collection { associatedtype Element associatedtype Index: Comparable = Int var count: Int { get } subscript(i: Index) -> Element { get } fn makeIterator() -> some Iterator<Element> var isEmpty: Bool { get => count == 0 } // default implementation}public protocol Sequence { associatedtype Element associatedtype Iter: Iterator where Iter.Element == Element fn makeIterator() -> Iter}- An associated type may have constraints, a default (
= Int), and awhereclause, which is the protocol's: it holds of every conformer. A conformer gives it with analias, or it is inferred from the conformer's members. - A protocol may refine others,
protocol Error: Debug, Sendable, and have generic parameters,Producer<out T>. - Conformance is nominal and explicit: a type conforms only where its declaration or an extension says so. A conformance may be declared only in the type's module or the protocol's (coherence).
- An
initrequirement may throw; a conformer meets it with one that throws that or nothing.
Unions#
UnionDecl = "union" Identifier [ ".." ] [ GenericParams ] [ ":" TypeList ] [ WhereClause ] UnionBody ; (* ".." marks a variant-sized union *)UnionBody = "{" { UnionCase } { MemberDecl } "}" ;UnionCase = { Attribute } Identifier [ "(" [ CasePayload ] ")" ] [ "," ] NL ;CasePayload = CaseField { "," CaseField } ;CaseField = [ Identifier ":" ] Type ;A union is a nominal tagged sum: a value is exactly one of its cases, each with an optional payload of labelled or unlabelled fields. Cases come first in the body, then members.
public union Shape { Circle(radius: F64) Rect(width: F64, height: F64) Poly(points: Vec2[>..]) Empty}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) } }}- A case is made as
Shape.Circle(radius: 2), or.Circle(radius: 2)where the type is known. - Unions may have methods, computed properties, static members and conformances, like structs.
- A recursive case is boxed automatically;
@indirecton a case, or the union, forces it. union Name..is variant-sized: each value takes exactly its case's size, so arrays of them are compact and sequential, and references may point into a payload; an existing value's case cannot be changed. See Inline Layout.- A public union that is not
@frozenmust be matched with adefaultin other modules.
Enumerations#
EnumDecl = "enum" Identifier [ ":" Type ] EnumBody ;EnumBody = "{" EnumCase { [ "," ] EnumCase } "}" ;EnumCase = { Attribute } Identifier [ "=" Expression ] ;An enum is a named integer: payload-free cases with an underlying integer value. The type after : is the integer type, Int if none.
public enum Direction { North, South, East, West }public enum Status: U8 { Pending = 0 Active = 1 Closed = 9}@flagspublic enum Permissions: U32 { None = 0 Read = 1 Write = 2 Execute = 4 All = Read | Write | Execute}- A case's value is the integer expression it is given — literals, earlier cases, and
| & ^ + - * << >> ~of them — or else one more than the previous case's, starting from 0; in a@flagsenum, the next bit up, starting from 1. Outside@flags, no two cases may share a value (S3142). Status.Closed as U8is a case's integer;9 as Statusis the case of an integer, trapping if there is none.- Interpolated, a case is its name. A
@flagsenum's value is any set of its cases, combined with| & ^ ~and tested withcontains; amatchon one needsdefault.
enum and union are deliberately separate: an enum is an integer, a union a tagged sum.
Extensions#
ExtensionDecl = "extension" Type [ ":" TypeList ] [ WhereClause ] TypeBody ;An extension adds members to an existing type — methods, computed properties, subscripts, operators, static members, nested types — and conformances. It may not add stored properties (nor field-backed ones) or designated initialisers.
extension String { var isBlank: Bool => trimmed().isEmpty init(twice s: String) { self = s + s }}extension Vec3: Serializable { }extension Array<T> where T: Comparable { fn sorted() -> Self { }}extension Collection { fn first(where predicate: (Element) -> Bool) -> Element? { }}- A struct's, enum's, union's or built-in type's extension may add an initialiser that gives
selfits value on every path (S3028). A class's may add aconvenience init(S3141), and no other (S3030). A protocol's may add none. - An extension of a protocol adds members to every conformer; a member that is not a requirement is dispatched statically.
- A conditional conformance:
extension Optional<T>: Serializable where T: Serializable { }.
Extending array kinds#
An array type has no name to put parameters after, so an extension of every array of a kind declares its parameters after the keyword:
extension<Element> Element[>..] { mutating fn appendTwice(_ e: Element) { append(e); append(e) }}extension<Element: Equatable> Element[:] { fn contains(element: Element) -> Bool { for x in self { if x == element { return true } } return false }}extension U8[:] { fn toHex() -> String { } }- Each kind is extended on its own:
T[],T[..],T[>..],T[>..<],T[:], with no size written. Members ofT[:]are every kind's. - Each parameter must appear in the array type. The members are an array's only where its element meets the constraints.
- A member for a specific element type is preferred over a generic one, and a more constrained one over a less.
- An extension of
T[>..]orT[>..<]may declare initialisers, starting fromself = [].
The grammar's ExtensionDecl does not show the extension<…> parameter list; the parser accepts it.
Type aliases#
AliasDecl = "alias" Identifier [ GenericParams ] "=" Type NL ;InitDecl = "init" [ "?" ] [ GenericParams ] "(" [ ParamList ] ")" [ ThrowsSpec ] [ WhereClause ] ( Block | NL ) ;An initialiser gives a new value every stored property before it returns (definite initialisation).
struct Temperature { var celsius: F64 init(celsius: F64) { self.celsius = celsius } init(fahrenheit: F64) { self.init(celsius: (fahrenheit - 32) * 5 / 9) } init(_ text: String) throws(ParseError) { celsius = try F64.parse(text) }}- An initialiser may be generic,
async,const,unsafe, and may throw (throws(E), barethrows,rethrows); a call to a throwing one is markedtry. - Delegation.
self.init(…)hands the work to another initialiser of the type; one that delegates leaves fields' initial values to the one it calls. - Classes. A subclass's initialiser calls
super.init(…)on every path, or delegates withself.init(…)(S3143); only a superclass made with the implicitinit()may be left to it.convenience initmust delegate (S3141).required initmust be implemented by every subclass. - Failure. An initialiser that throws part way made nothing: the fields it had set are destroyed, the others left alone, and no
deinitruns (for a class, its own or a superclass's). - The grammar admits
init?, a failable initialiser; the language does not yet give it a meaning, so it should not be used.
Deinitialisers#
DeinitDecl = "deinit" Block ;deinit runs as a class instance's last reference goes, or as a @noncopy value is destroyed. It takes no parameters and cannot be called directly.
Properties and accessors#
PropertyDecl = ( "let" | "var" ) Identifier ":" Type Accessors ;Accessors = "{" ( GetSetBlock | ObserverBlock | "get" [ "set" ] ) "}" ;GetSetBlock = GetAccessor [ SetAccessor ] | SetAccessor GetAccessor ;GetAccessor = { Attribute } [ Visibility ] "get" ( Block | "=>" Expression | NL ) ;SetAccessor = { Attribute } [ Visibility ] "set" [ "(" Identifier ")" ] ( Block | NL ) ;ObserverBlock = { ( "willSet" | "didSet" ) [ "(" Identifier ")" ] Block } ;class Temperature { private var celsius: F64 = 0 var fahrenheit: F64 { get => celsius * 9 / 5 + 32 set { celsius = (newValue - 32) * 5 / 9 } } var kelvin: F64 => celsius + 273.15 // get-only shorthand private(set) var updates: Int = 0 var tracked: Int = 0 { willSet { log("becoming \(newValue)") } didSet { log("was \(oldValue)") } } lazy var report: Report = computeReport()}| Kind | Declared with | Meaning |
|---|---|---|
| Stored | let/var name: T = v, or name: T |
A field of the value |
| Computed | { get … set … } |
Read and written through accessors; no storage |
| Get-only shorthand | var name: T => e |
{ get => e } |
| Observed | { willSet … didSet … } after a stored var |
Stores call willSet (with newValue) then didSet (with oldValue) |
| Field-backed | accessors naming field |
Stored, but read and written through its accessors |
| Lazy | lazy var name: T = e |
e evaluated on first read, and kept |
- Accessors. Either may be
=> eor a block. A setter's new value isnewValue, or the name it gives inset(name). An accessor may have its own visibility, andprivate(set)on the property restricts its setter. - Observers run for compound assignment too, but not for stores the observers make themselves, nor in the type's initialisers, a record literal or the memberwise initialiser. An observed property is a
var, declares nogetorset, and belongs to a struct, class or actor (S3140). field. Accessors may refer tofield, storage of the property's own. The property must then have an initial value.getorsetwritten alone is the plain one (get => field,set => field = newValue). An extension cannot declare one.lazy. Alazy varhas an initialiser, which may useself, and no accessors; it belongs to a struct, class or actor (S3113). Since reading a struct's lazy property writes it, it is read only from avaror in amutatingmethod.- A brace after a stored property's initialiser opens accessors when it starts with
get,set,willSetordidSet; otherwise it is a trailing closure on the initialiser. weak varof a class type is optional and becomesnonewhen the object is released;unownedis not optional, and traps when read after release;unowned(unsafe)does not check.- Static stored properties are initialised before
main, like globals.
Subscripts#
SubscriptDecl = "subscript" [ GenericParams ] "(" [ ParamList ] ")" "->" Type [ WhereClause ] ( Accessors | "=>" Expression NL ) ;A subscript lets an instance be indexed, grid[x: 1, y: 2]. Its parameters follow function rules, including labels; its accessors follow property rules.
struct Grid<T> { subscript(x: Int, y: Int) -> T { get => storage[y * width + x] set { storage[y * width + x] = newValue } } subscript(row r: Int) -> T[:] => storage[r * width ..< (r + 1) * width]}Operator declarations#
OperatorDecl = [ "prefix" | "postfix" ] "operator" OperatorSymbol "(" [ ParamList ] ")" "->" Type ( Block | "=>" Expression NL ) ;OperatorSymbol = "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^" | "<<" | ">>" | "==" | "!=" | "<" | "<=" | ">" | ">=" | "[" "]" | "(" ")" | "!" | "~" ;A type may overload operators for its values, as members taking every operand as a parameter:
struct Money { var cents: Int operator + (a: Money, b: Money) -> Money => Money(cents: a.cents + b.cents) operator == (a: Money, b: Money) -> Bool => a.cents == b.cents operator < (a: Money, b: Money) -> Bool => a.cents < b.cents prefix operator - (m: Money) -> Money => Money(cents: -m.cents)}- Overloadable: binary
+ - * / % & | ^ << >> == != < <= > >=,[](an alternative subscript form) and(), and prefix- ! ~. - Not overloadable:
&& || ?? ?. = . as is, and compound assignments, which are derived from the binary operator. postfix operatordeclarations parse, but a user-declared postfix operator is resolved only for!; treat them as limited.- There are no custom operator symbols, and precedence is fixed.