On this page (15 sections)
- 5.1 Operator precedence
- 5.2 Arithmetic, comparison, logical, bitwise
- 5.2.1 Numeric conversion
- 5.3 Assignment
- 5.4 Member access & methods
- 5.5 Subscript expressions
- 5.6 Function calls
- 5.7 Struct construction
- 5.8 Enum construction
- 5.9 Match expression
- 5.10 if as expression
- 5.10.1 Unit expressions
- 5.11 Closures
- 5.12 Nil-coalescing ??
- 5.13 String interpolation
§5 Expressions
5.1 Operator precedence
From highest (binds tightest) to lowest. Same-row operators have equal precedence; associativity is shown.
| Level | Operators | Associativity |
|---|---|---|
| 1 | . (...) [...] postfix ? postfix ! | left |
| 2 | prefix ! prefix - prefix ~ | right |
| 3 | as as? &as (numeric conversion, §5.2.1) | left |
| 4 | * / % | left |
| 5 | + - | left |
| 6 | << >> | left |
| 7 | & (bitwise) | left |
| 8 | ^ | left |
| 9 | | | left |
| 10 | ..< ... | none |
| 11 | < <= > >= | none |
| 12 | == != | none |
| 13 | && | left |
| 14 | || | left |
| 15 | ?? (nil / .Err coalescing) | right |
| 16 | assignment (= += …) | right |
(Postfix ? propagates Result/Optional failure; postfix ! forces an unwrap. Optional chaining is the separate ?. form; see §5.4 and §8.3.)
5.2 Arithmetic, comparison, logical, bitwise
Standard semantics. Integer overflow on signed types is a trap in all builds (debug and release alike) — the behavior never changes with the optimization level (§0.1 principles 4 & 5). Programmers may opt into two's-complement wrapping with &+, &-, &* (reserved syntax ⏳, deferred to v0.2).
Comparisons are non-chaining: 1 < x < 10 is a syntax error.
== and != are defined through the Equatable protocol (§20.13): they take two operands of one type that conforms, and != is the negation of ==. The builtin scalars, String and Void conform; a user structure or enumeration conforms only by declaring it, X?, Result<X, Y> and [X] conform when their components do, and function types and Dict never conform. Other operands are rejected with type-checking.invalid-operator-operands. Neither operand takes the enclosing expected type: an operand with no type of its own (nil, .Red, [], a literal) is typed by the other operand, on either side. The left operand is evaluated before the right; how each is accessed is in §20.13.2. x == nil and x != nil test an optional's presence whatever its payload (§20.13.4). Float and Double equality is IEEE 754 equality: a NaN is not equal to itself, and -0.0 == 0.0. Signed Int division (/) truncates toward zero. The remainder (%) is zero or has the sign of the dividend; when defined, a == (a / b) * b + a % b. Both operators trap when the divisor is zero. Both also trap for the minimum Int and divisor -1, including remainder even though its mathematical result would be zero. These checks apply in every optimization mode.
Bitwise &, |, ^ take two integers of the same type; prefix ~ takes one integer. << and >> take an integer on the left and an integer of any type as the shift count. A count that is negative or not less than the bit width of the left operand traps in every build. >> is arithmetic for signed types and logical for unsigned types; << discards bits shifted out and never traps for that reason.
Prefix ! takes a Bool and returns its negation. Logical && and || take Boolean operands and produce Bool.
Logical && evaluates its left operand first and evaluates the right operand only when the left is true. The skipped operand produces no side effects, traps, ownership transfers, or early returns. The result is false when the left operand is false, independently of optimization level.
Logical || evaluates its left operand first and evaluates the right operand only when the left is false. Its result is true when the left is true; the same skipped-side-effect and cleanup rules apply. && binds more tightly than ||. Prefix negation is not postfix force unwrap, which remains deferred.
5.2.1 Numeric conversion
The numeric types are the integer types (Int, UInt, Int8..Int64, UInt8..UInt64) and the floating-point types (Float, Double). Non-numeric types (Bool, Char, String, structs, enums, function types, type parameters, Void, and Never) are rejected on either side of a cast.
x as Tconverts a numeric expressionxto numeric typeT:- Integer to integer: traps with
"integer conversion out of range"in every build when the value is not representable inT. - Integer to
Float/Double: converts using IEEE 754 round-to-nearest, ties-to-even, and never traps. Large 64-bit integers may lose low significand bits. Float/DoubletoFloat/Double: identity casts preserve the exact IEEE 754 value (including-0.0andNaN);FloattoDoubleis exact;DoubletoFloatuses IEEE 754 round-to-nearest, ties-to-even (values exceedingFloat's finite range produce signed infinity;NaNremainsNaN). Never traps.Float/Doubleto integer: truncates toward zero (dropping any fractional part) and traps with"float conversion out of range"in every build whenxisNaN, infinite, or its truncated integer value is outside[T.min, T.max]. (Thus-0.9 as UInt8is0,-128.9 as Int8is-128,-1.0 as UInt8traps, and-129.0 as Int8traps.)
- Integer to integer: traps with
x &as Tconverts between integer types only: it keeps the low bits when narrowing and extends by the source type's signedness when widening, never trapping. Using&aswithFloatorDoubleon either side (even as an identity cast) is a compile-time error.x as? TreturnsResult<T, ConversionError>:.Okwith the same valuex as Twould produce, or.Err(.OutOfRange)wheneverx as Twould trap, never trapping.ConversionErroris a prelude enum with the single caseOutOfRange; use postfix?to propagate it, ormatchto handle it.as?checks only target integer range (andNaN/infinity for float-to-integer): fractional parts are truncated (1.5 as? Intis.Ok(1)), and total conversions (widening/identity integers, integer to floating-point, and floating-point to floating-point, includingDoubletoFloatoverflow to infinity) always return.Ok.
T is a plain type name. A cast binds tighter than binary operators and looser than prefix operators: a + b as UInt32 << 8 is (a + (b as UInt32)) << 8, and -x as T is (-x) as T.
Literal operands. With as (for any numeric T) and &as (for integer T), an integer literal (optionally negated or parenthesized) takes target type T. With as, a floating-point literal (optionally negated or parenthesized) takes target type T when T is Float or Double; an out-of-range or unrepresentable literal (such as 300 as UInt8 or 1e40 as Float) is a compile-time error. A floating-point literal cast to an integer type (1.9 as Int, -0.9 as UInt8, 300.0 as UInt8) stays Double and converts via truncation and range checking. With as?, integer literals stay Int and floating-point literals stay Double, so out-of-range literals evaluate to .Err(.OutOfRange) (300 as? UInt8, 300.0 as? UInt8, -1.0 as? UInt8).
5.3 Assignment
assignment ::= [ '&' ] lvalue assign_op expression
assign_op ::= '=' | '+=' | '-=' | '*=' | '/=' | '%='
| '&=' | '|=' | '^=' | '<<=' | '>>='
The & prefix is required whenever the assignment target is a mutable projection that the writer does not own outright — an inout / initializing parameter binding, or a projection through an inout / initializing subscript:
&a[0] = 10 // subscript inout projection — & required
&n += 1 // n is an `inout` parameter — & required
p.x = 10 // direct field on a local `var` binding — no & needed
count = count + 1 // direct local `var` — no & needed
Heuristic. Write
&when the assignment targets aninout/initializingparameter or storage reached through asubscript. Omit&only when assigning directly to a localvaror a direct field of a localvar. (Reads never take&; the marker is about the write target.) The compiler reports the required form in any case.
5.4 Member access & methods
member_expr ::= postfix_expr '.' identifier
optional_chain ::= postfix_expr '?.' identifier
Methods declared in a struct, enum, or extension are called via member syntax: a.size(), point.distance(to: other).
a.f(args) always calls a method. When a has a type-parameter type (§20.4), the method is a requirement of a protocol in its constraint and the call reaches that requirement's witness (§20.5, §20.6). A stored field of function type is called with a parenthesized callee, (a.f)(args) (§5.6.1). A type may not have a stored field and a method with the same name (name-resolution.duplicate-declaration).
Optional chaining short-circuits to nil:
let lengths = optionalString?.count // type: Int?
5.4.1 The ? / ! forms
The ? and ! forms, nil, and implicit wrapping bind to the declarations carrying the optional and result roles (§2.4, §2.5), never to a name that happens to be in scope.
| Form | Meaning | Section |
|---|---|---|
T? | optional type (Optional<T>) | §2.4 |
x?.field | optional chaining | §5.4 |
expr? | Result / Optional propagation (early return) | §8.3 |
x ?? y | coalescing with fallback y | §8.5 |
x! | force-unwrap (traps on nil) | §2.4 / §9.3 |
5.5 Subscript expressions
subscript_expr ::= postfix_expr '[' expression , ... ']'
Resolves to the matching subscript declaration. The accessor invoked depends on the surrounding context (§4.5.1).
5.6 Function calls
call_expr ::= callee '(' [ call_arg , ... ] ')'
callee ::= identifier | member_expr | '(' expression ')'
call_arg ::= [ label ':' ] [ '&' | 'consume' ] expression
Argument labels are mandatory at every call by name (§3.2.1); there is no positional / unlabeled form for one and no _ label. func f(a: Int, b: Int) must be called as f(a: 1, b: 2). Supplied arguments follow declaration order; a defaulted argument (§3.2.5) may be omitted but is never written without its label. Unlabeled arguments appear only in a call through a function value (§5.6.1) and in enum construction (§5.8).
5.6.1 Function values and calls through them
The layout intrinsics of §20.12.5 are compiler-known functions, not function values: they can only be called, and only in toolchain-authorized units.
The name of a function, used as an expression where it is not called, is a function value of its function type (§2.3.1, decision 0020):
func square(value: Int): Int { value * value }
func bump(count: inout Int) { count = count + 1 }
let f = square // f: (Int): Int
let g: (inout Int): () = bump
var n = f(3) // 9
g(&n) // n == 10
A module-qualified name works too. Only the name's visibility is checked (§12.2); a private function's value may be returned by a public function.
These are not function values (type-checking.not-a-function-value, which states the reason):
- methods, declared and synthesized initializers, and enum cases;
- the compiler-known builtins (
print,byteToInt,byteToString) and the runtime intrinsics (§19.4.5); a user declaration that shadows a builtin is an ordinary function and is a value; @c_externand@c_datadeclarations (§19.5);- the root module's
main(§3.2.6); a dependency'smainis ordinary.
The prelude spawn and channel are generic source-library functions (§21), not builtin functions; the ordinary prohibition on generic function values (§20.4.1) still applies to them.
A function's default parameter values (§3.2.5) do not carry over: a call through the value supplies every argument.
Calls. A function value named by a plain identifier is called directly: f(a, &b, consume c). Any other callee is parenthesized: (s.handler)(x), (table[i])(x), (maybe!)(x); s.f(args) always names a method (§5.4).
- Arguments are positional. A label is an error (
type-checking.labeled-function-value-call), and so is a wrong number of arguments. - Each argument is checked against its parameter's type and effect exactly as for a call by name (§4.2, §4.3):
inoutandinitializingarguments are written&x;consumingarguments requireconsume xfor place expressions and omitconsumefor rvalue temporaries. - Evaluation order. The callee expression is evaluated first, to a copy; no access to its storage is held while the arguments are evaluated or during the call. The arguments are then evaluated left to right and committed as for a call by name (§4.4, §4.7.1). So
(s.f)(&s)and(handlers[0])(&handlers)are valid. - A call whose result type is
Neverdoes not return. - An optional function value must be unwrapped first, with
(maybe!)(x)or amatch.maybe?(x)propagatesnilout of the enclosing function and then calls (§5.4.1); it is not "call if present". - Calling a value that is not a function is
type-checking.not-callable.
5.6.2 Trailing collection block calls
A call whose callee is a function or method with a @collect final parameter (§3.2.8, decision 0042) may supply that parameter as a trailing_block { statement* } immediately on the same physical line after (...), or directly after the callee identifier or postfix_expr '.' identifier when every preceding parameter has a default value (or none exist). Trailing blocks are disallowed at the top level of if/while conditions, for sources (including range bounds), and match scrutinees unless enclosed in parentheses or another delimiter.
Passing a trailing block to any other callee (including function values, enum cases, and protocol-constrained method calls) is type-checking.unexpected-trailing-block. Supplying both the labeled final argument and a trailing block is type-checking.duplicate-collect-argument. A trailing block supplies no consume marker even when the parameter is consuming.
Generic inference (§20.4.1). A trailing @collect block carries no type of its own (ArgumentInformation::none, strength 0 in ==/!= §20.13.2): callee type parameters appearing in [T] must be determined by other arguments or the enclosing expected return type before checking the block. If the substituted element type T is concrete Void, the call is rejected (type-checking.invalid-collect-parameter).
Evaluation and exclusivity. Receiver, earlier arguments, omitted defaults (§3.2.5), and the trailing block evaluate left to right in declaration order. If an earlier argument or default diverges or exits, the block does not execute. Inside the block, exclusivity (§4.4) and consume commit (§4.7.1) apply exactly as for an explicit final argument expression.
Block semantics. The compiler initializes an empty local var $items: [T] = [] in the caller's frame and checks statements in the block recursively:
let/varbindings execute normally and contribute no elements (their initializers are ordinary value expressions).- Bare
if/else if/elsestatements check each branch recursively as a@collectblock (elseis optional; branches need not share a type). - Bare
matchstatements check exhaustiveness and patterns as in §5.9 and check each arm body (block or single expression) recursively as a@collectconstruct. for,while, and nested{ ... }blocks check their bodies recursively as@collectblocks.- An
iformatchnested inside another expression (e.g.let x = if ...,(if ...), call arguments) keeps ordinary value-expression semantics. - Any other expression statement
eis checked once with expected type: none for assignments;[T]for array literals whenTis not[U], and for generic calls (through(...),consume,?) whose declared return type fails structural matching againstTbut matches[T]; andTotherwise. Its typeUis classified in order:Never: diverges (subsequent statements unreachable).- Assignable to
T(including implicitOptionalwrapping, §2.4): appends one element to$items. [T]: splices every element into$itemsin order.Void: executes for side effects; contributes no elements.- Otherwise:
type-checking.invalid-collect-element.
- Ownership of appended
Tand spliced[T]: an owned temporary or explicitconsume placemoves/drains into$items(valid for copyable and noncopyableT); an unmarked place copies into$itemsifTis copyable and istype-checking.copy-of-noncopyableotherwise. - Exits:
return,?,break, andcontinuetarget the enclosing function or nearest enclosing loop (§6.4, §6.5), deterministically destroying$itemsand earlier pending temporary arguments in reverse order.
When the block completes normally, $items is passed as the final argument (borrowed if borrowing, then destroyed after the call; moved if consuming).
5.7 Struct construction
let p = Point(x: 1.0, y: 2.0) // explicit init or synthesized
let q = Point(x: 0.0, y: p.y)
5.8 Enum construction
enum_ctor_expr ::= [ type ] '.' identifier [ enum_payload_clause ]
enum_payload_clause
::= '(' enum_arg , ... ')'
enum_arg ::= [ label ':' ] expression
let command: Message = .Move(x: 3, y: 4) // contextual: target type known
let text = Message.Text("ready") // fully qualified
let error: DecodeError = .Unexpected(b'?', at: 12)
The declaration determines the payload arity and labels. A payload position declared without a label is positional; a labeled position must use exactly that label. Positional and labeled payloads may be mixed in declaration order. Besides calls through a function value (§5.6.1), this is the only unlabeled invocation form; calls by name and struct-initializer calls require labels (§3.2.1, §5.6). A payload-less case is written without an empty argument clause (.Quit, not .Quit()).
5.9 Match expression
match_expr ::= 'match' expression '{' match_arm+ '}'
match_arm ::= pattern ( ',' pattern )* [ 'where' expression ] '=>' (expression | block) ','?
match is an expression; every arm must produce a value of the same type (or all be Void). An arm may list several comma-separated alternative patterns and runs when any of them matches (§7.2):
enum Reading {
Missing,
Value(Int),
}
let label = match reading {
.Missing => "missing",
.Value(n) where n < 0 => "negative",
.Value(_) => "non-negative",
}
Exhaustiveness is checked (§7.7).
Because return is a diverging expression (§2.9, §6.4), it may be an arm body:
let value = match result {
.Ok(value) => value,
.Err(error) => return .Err(error),
}
5.10 if as expression
if/match are expressions; while/for are statements.
let sign = if x > 0 { 1 } else if x < 0 { -1 } else { 0 }
Every branch must produce the same type. The whole if-else must be total (i.e., have an else arm) when used as an expression. An if or match whose value is unused, such as one in statement position, discards the value of the branch that runs; a branch that names a noncopyable place then does not copy it (§4.1.1).
5.10.1 Unit expressions
An empty pair of parentheses in expression position, (), is the unit value of type Void (§2.1.2), not a missing expression or a general tuple. Parenthesized expressions such as (value) keep their existing meaning. In .Ok(()), the outer parentheses contain one payload expression, (); .Ok() is not an alternative unit construction.
5.11 Closures
Closures are deferred to v0.2. A function value (§5.6.1) refers to a top-level function and captures nothing; higher-order code passes such values, or a struct together with a function value when it needs context.
5.12 Nil-coalescing ??
The coalescing operator ?? binds to the optional and result roles (§2.4, §2.5, §5.4.1) and supplies a fallback for an absent Optional or a failed Result (§8.5). It is right-associative at precedence level 15 (§5.1, looser than || and comparisons), so a ?? b ?? c parses as a ?? (b ?? c). The left operand a is evaluated once; b is evaluated only when a is .None or .Err (short-circuit), after any borrow of a has ended. When the error of a Result must be inspected rather than discarded, use match or ? (§8.3).
let port: Int = parseInt(s: s) ?? 8080 // plain fallback value
let v = parseInt(s: s) ?? fatalError(message: "bad input") // fallback diverges (Never, §2.9)
let c = peek(p: p) ?? return .Err(.UnexpectedEof) // fallback returns from the caller
- Typing.
ais checked first without an expected type and must have typeOptional<T>orResult<T, E>.- For
a: Optional<T>: ifbis a barenilliteral,btakes typeTwhenTis itself anOptional(unwrapping one layer toT), orOptional<T>otherwise (producingT?). For any otherb,bis checked with expected typeT; the result isTwhenbhas typeNeveror is assignable toT, orOptional<T>whenbhas typeOptional<T>. - For
a: Result<T, E>:bis checked with expected typeT; the result isTwhenbhas typeNeveror is assignable toT, orResult<T, E2>whenbhas typeResult<T, E2>. MixingResultandOptionalacross??(unless the innerTmatches) is a type error (§8.3).
- For
- Ownership and linearity.
??is rejected on any linear left operand (§4.7.1), includingOptional<Linear>,Result<Linear, E>, andResult<T, LinearErr>; usematch. WhenTis noncopyable (affine),amust be an owned temporary or explicitlyconsumed (consume a ?? b); whenTis copyable (even forResult<T, NonCopyErr>),amay be borrowed withoutconsume. A noncopyablebmust be an owned temporary orconsume b(which conditionally consumesbon the fallback path). Any owned.Err(e)payload is deterministically destroyed before leaving the expression.
5.13 String interpolation
A string_interpolation expression (§1.7, decision 0046) always has static type String and produces an independent owned String value.
- Typing. Each interpolated expression
e_iis checked with no expected type (numeric literals default toIntorDoubleper §2.8;nil, bare.Case,[], or[:]reporttype-checking.missing-contextual-type). Admitted operand types are:String: appended verbatim.- Signed integers (
Int,Int8,Int16,Int32,Int64): base-10 decimal with a leading-when negative (identical toprint). - Unsigned integers (
UInt,UInt8,UInt16,UInt32,UInt64): base-10 decimal (identical toprint; in particularUInt8formats as0..255, not as a character — usebyteToString(value:)for a single byte). Float:%.9gformatting (9 significant digits; identical toprint).Double:%.17gformatting (17 significant digits; identical toprint).Bool:"true"or"false"(identical toprint).Char(UTF-8 encoded scalar, when implemented).Never: diverging expression; the enclosing interpolation keeps static typeStringwhile control-flow analysis treats it as diverging, so subsequent segments and expressions are unreachable.
Any other type is rejected with
type-checking.invalid-interpolation-operand. - Evaluation order, borrowing, and exclusivity. Literal segments and interpolated expressions evaluate strictly left to right. Each
e_iis evaluated in a borrowing context ("\(consume s)"istype-checking.invalid-consume-argument, while consuming method calls and consuming call arguments insidee_iremain valid). Eache_icompletes before the next begins, so later segments may borrow or mutate storage accessed earlier ("\(bump(n: &x)) \(x)","\(s) \(mutate(s: &s))"). Earlier string content is materialized before any subsequent expression runs. Single-piece"\(s)"produces an independent ownedString. Early exits (return,?) deterministically destroy any already-built prefixStringand temporaries in reverse order (§4.7). - Restrictions. A
string_interpolationis not a compile-time constant expression (§3.1.1) and is rejected in runtime core units (--runtime-core-module, §19.4.7,type-checking.managed-type-in-core-unit).