DocsLanguage Reference
Expressions
Every kind of expression, operator precedence, literals and how the compiler reads braces.
An expression computes a value, and may have effects on the way. Sable's expressions are built from primary expressions — literals, names, closures, if and match — combined by postfix operations (member access, calls, subscripts, casts), prefix operators and binary operators whose precedence is fixed by the grammar. This chapter lists every kind of expression and the rules for each.
Most of this is taught in the guide: operators in Basic Operators, interpolation in Strings and Characters, closures in Closures, try in Error Handling, casts and metatypes in Casting, Metatypes and Reflection.
Expression = AssignExpr ;Operator precedence#
From tightest to loosest:
| Level | Operators | Associativity |
|---|---|---|
| 1 | a.b a?.b a! a[i] a?[i] f(x) f?(x) a as T a as? T a as! T a unchecked as T a is T |
left (postfix) |
| 2 | prefix -a +a !a ~a &a ^a await a move a, and try a |
right (prefix) |
| 3 | * / % &* |
left |
| 4 | + - &+ &- |
left |
| 5 | << >> |
left |
| 6 | ..< ... |
none |
| 7 | < <= > >= |
left |
| 8 | == != === !== |
left |
| 9 | & |
left |
| 10 | ^ |
left |
| 11 | | |
left |
| 12 | && |
left |
| 13 | || |
left |
| 14 | ?? |
right |
| 15 | a ? b : c |
right |
| 16 | = and every compound assignment |
right |
Some consequences:
- Casts are postfix:
-x as I64is-(x as I64), anda + b as F64isa + (b as F64). - The bitwise operators bind looser than comparison, as in C:
flags & mask == 0isflags & (mask == 0). Parenthesise. - A range binds looser than arithmetic and shifts, so
0..<n - 1is0..<(n - 1), and tighter than comparison. tryis written as a prefix but covers the whole expression to its right, stopping short of an assignment:x = try a() + b()assigns the sum of two calls that may both throw.
There are no custom operators and no way to change precedence. The binary operators that may be overloaded are listed in Declarations.
Literal expressions#
Literal = NumericLiteral | StringLiteral | CharLiteral | BoolLiteral | "none" ;TupleExpr = "(" [ TupleElem { "," TupleElem } ] ")" ;TupleElem = [ Identifier ":" ] Expression ;ArrayLiteral = "[" [ Expression { "," Expression } [ "," ] ] "]" ;DictLiteral = "[" ":" "]" | "[" KeyValue { "," KeyValue } [ "," ] "]" ;KeyValue = Expression ":" Expression ;RecordLiteral = QualifiedName "{" [ FieldInit { "," FieldInit } [ "," ] ] "}" ;FieldInit = Identifier ":" Expression ; (* no shorthand: '{ x }' would be a closure returning x *)Every literal form, side by side (a list to read, not a program):
42 0xFF 0o755 0b1010_0110 1_000_000 // integers3.14 1e-9 0x1.8p3 // floatstrue false none'a' '\n' '\u{1F600}' // characters"text" "with \(interpolation) inside" #"raw"# // strings[1, 2, 3] // array["a": 1, "b": 2] // dictionary[:] // empty dictionary[String: Int]() // empty dictionary, by its type's init()Int[>..]() // empty grow-only array; likewise Int[>..<]()(1, "two", 3.0) // tuple(q: 7, r: 1) // labelled tuple.Circle(radius: 1) // union case, inferred from contextPoint { x: 1, y: 2 } // record literalThe token forms are specified in Lexical Structure. The rules for the compound ones:
- Typing. A literal has the type its context asks for. An expression of literals alone, such as
29 << 112or~0, does too: the type of theletit initialises, of the parameter once the overload is chosen, or of the other operand. With no context, integers areIntand floatsF64. An array literal's elements take the element type the context asks for, or else the type of its other elements. A tuple literal passed for a tuple parameter takes the parameter's element types:let p: (F32, F32) = (0, 1). - Trailing commas are allowed in array, dictionary and record literals and in argument lists.
- Arrays. An array literal makes whatever array kind the context asks for. An inline array
T[k]is made from a literal of exactlykelements. Passed where the elements are an existential, each element is converted:let xs: (any Any)[] = [1, "a"]. A@flagsenum's value is written as an array of its cases,[.Read, .Write], or[]for none. [:]is the empty dictionary wherever a dictionary is expected;[]the empty array.- Empty collections by type. A dictionary type and a growable array type may be called to make an empty one:
[String: Int](),Int[>..](),Int[>..<](). Other compound types are not called. - Record literals set every stored field of a struct (or class) by name,
Point { x: 1, y: 2 }; the type name may be qualified or generic,Ring<Int, 2> { slots: [1, 2] }. A field always carries its value: there is no shorthandPoint { x, y }, because{ x }would be a closure. A field with an initial value may be left out. Observers do not run for fields a record literal sets.
Interpolation and format specs#
A hole \(expr) in a string literal writes its value: a string as it is; a number, Bool or Char as text; a Formattable value as its format writes it; an enum as its case's name; a Debug value as it describes itself; anything else as Reflect.describe does.
A colon after the expression starts a format spec, raw text running to the hole's ). A colon that belongs to the expression (a ternary's) is the expression's own: "\(ok ? a : b:x)".
FormatSpec = [ [ Fill ] Align ] [ "+" | "-" | " " ] [ "#" ] [ "0" ] [ Digits ] [ "," | "_" ] [ "." Digits ] [ "d" | "x" | "X" | "o" | "b" | "e" | "E" | "f" | "g" | "G" | "%" | "?" ] ;Align = "<" | "^" | ">" ;Fill = ? any scalar but '"', "'", "\", "(" and ")" ? ;| Part | Meaning |
|---|---|
fill align |
< left, ^ centre, > right (default: numbers right, text left), padded with fill (default a space) |
sign |
+ every number signed; - only negative ones (default); a space where + would be |
# |
An integer's radix prefix (0x, 0o, 0b); for g, trailing zeros kept |
0 |
Pad a number with zeros after its sign, to the width |
width |
The least number of scalars written |
, or _ |
A separator every three digits of the whole part (every four in another radix, for _) |
.precision |
Digits after a float's point (all digits, for g); scalars kept, for a string |
kind |
d x X o b integers; e E f g G % floats; ? anything, as Debug |
"\(n:#06x)" // 0x00ff"\(price:>10.2)" // right-aligned in 10, two decimals"\(total:,)" // 1,234,567"\(ratio:.1%)" // 12.5%"\(name:*^9)" // **sable**"\(value:?)" // as Debug describes itA float without a precision is written in the shortest digits that read back as the same value; with one, rounded to nearest, ties to even. The spec becomes a FormatSpec passed to Formattable.format, so a type of your own can honour it. The compiler checks it: a malformed spec is S3660, a kind the type is not written in S3661, an option the type would ignore (a precision on an integer) S3662, and anything but fill, alignment, width or ? on a type that is not Formattable S3663.
Primary expressions#
PrimaryExpr = Literal | Identifier [ GenericArgs ] | "self" | "super" | "Self" | "." Identifier [ "(" [ ArgumentList ] ")" ] (* inferred member *) | KeyPathExpr | "(" Expression ")" | TupleExpr | ArrayLiteral | DictLiteral | RecordLiteral | ClosureExpr | MatchExpr | IfExpr | TryExpr | "unsafe" Block | Type "." "self" | CalledType "(" [ ArgumentList ] ")" (* its initialiser *) | "#" Identifier ; (* compiler builtins: #file, #line *)- Names. An identifier names a local, parameter, member of
self, function, type or module item. A generic function or type may be given explicit arguments:Stack<Int>(),parse<Int>(text). selfis the current instance in a member;superreaches the superclass's members,super.init(…);Selfis the enclosing type,Self(x: 3),Self.zero.- Builtins
#file,#line,#column,#function,#moduleand#expressionare listed in Lexical Structure. - Parentheses group; a parenthesised list is a tuple.
unsafe { … }in expression position is an unsafe block whose value is its last expression; see Statements.
Prefix operators#
UnaryExpr = PrefixOp UnaryExpr | PostfixExpr ;PrefixOp = "-" | "+" | "!" | "~" | "&" | "^" | "await" | "move" ; (* prefix '^' counts from the end: '^1', a FromEnd *)| Operator | Meaning |
|---|---|
-a |
Negation; traps on overflow (-Int.min) |
+a |
The value itself |
!a |
Logical not, of a Bool |
~a |
Bitwise not, of an integer or a @flags enum |
&a |
A reference to the place a, or an argument the call may write |
^n |
The position n from the end of a collection, a FromEnd |
await a |
Waits for an async call |
move a |
Moves the value out of a |
Each is described under its own heading below. Prefix -, ! and ~ may be overloaded (see Declarations).
Binary operators#
Arithmetic#
+, -, *, / and % work on numbers of one type; there is no mixed-type arithmetic. On integers +, - and * trap on overflow. + also concatenates strings.
The wrapping operators &+, &- and &* give a fixed-width integer's result with the low bits kept, never trapping. They are FixedWidthInteger's, and bind as + and * do. & followed by +, - or * is always one of these tokens, so a bitwise and with a negated operand needs a space: a & -b.
Bitwise and shifts#
&, |, ^ and ~ are and, or, exclusive or and not, on integers and on @flags enum values. << and >> shift.
Comparison and identity#
==, !=, <, <=, >, >= compare Equatable and Comparable values. === and !== compare identity, whether two class references are the same object; they apply to class instances only.
Logical#
&& and || take Bools and short-circuit: the right operand is evaluated only when needed.
Nil-coalescing#
a ?? b is the value a holds, or b when a is none; b is evaluated only then. When b is a T, the result is a T; when b is a T? too, the result is a T?. It is right-associative, so a ?? b ?? c tries each in turn. b may be a throw expression: configured ?? throw ConfigError.Missing("port").
Ranges#
RangeExpr = ShiftExpr [ ( "..<" | "..." ) [ ShiftExpr ] ] | ( "..<" | "..." ) ShiftExpr ;| Expression | Range |
|---|---|
a..<b |
Half-open: a up to but not including b (Range) |
a...b |
Closed: a through b (ClosedRange) |
..<b |
Partial, from the start |
a... |
Partial, to the end |
Ranges do not associate. A range of integers is a random-access collection of them, so (0..<n).reversed() counts down. There is no unbounded range (xs[...]): xs itself is the whole collection, or xs[..<^0] a slice of all of it. Where a brace opens a statement body, for i in 3... { is a range with no upper bound followed by the body.
A bound may be counted from the end, xs[1..<^1]; such a range is a RelativeRange, resolved against the collection it slices.
The conditional operator#
TernaryExpr = CoalesceExpr [ "?" Expression ":" TernaryExpr ] ;c ? a : b evaluates c, a Bool, then exactly one of a and b, which must have one type. It is right-associative. The ? must have a space before it, or it would begin optional chaining. A long one may break before ? or :.
Assignment#
AssignExpr = TernaryExpr [ AssignOp AssignExpr ] (* right assoc *) | "_" "=" AssignExpr ; (* dropped *)AssignOp = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "??=" | "&+=" | "&-=" | "&*=" ;target = value stores value in a place: a var, an inout parameter, a field or element of one, a property or subscript with a setter, or what a reference that writes refers to. Storing to a let place is refused (S3010). An assignment gives no value.
- Compound assignment
a op= bisa = a op b, with whatais made of evaluated once, before the right side:xs[next()] += f()callsnextonce, reads the element, callsf, and stores where it read. Compound assignment is derived from the binary operator and cannot be overloaded on its own. a ??= bstoresbin the optionalaonly ifaisnone;bis evaluated only then._ = eevaluateseand drops the result: the value is made and destroyed. It is how the result of a function that is not@discardableis ignored on purpose._is an expression nowhere else.- A store to a growable array's range replaces the range with as many elements as are stored,
xs[1..<3] = [7]; any other array, or a slice, stores element by element and needs the range's count, or traps.
var retries: Int? = noneretries ??= 3total += price * 2_ = cache.remove(key)Postfix expressions#
PostfixExpr = PrimaryExpr { PostfixOp } ;PostfixOp = "." MemberName [ GenericArgs ] | "?" "." MemberName | "!" | "(" [ ArgumentList ] ")" [ TrailingClosure ] | "?" "(" [ ArgumentList ] ")" | "[" ArgumentList "]" | "?" "[" ArgumentList "]" | TrailingClosure ;A postfix operation must start on the same line as what it applies to, or the line would end the statement — except . and ?., which continue a statement from the next line.
Member access#
MemberName = Identifier | Keyword ; (* any keyword may name a member: 'super.init', 'T.self' *)a.b reads a member of a: a stored or computed property, a method, a static member of a type, a case of a union or enum, an item of a module. Any keyword may be a member name after ., because the name is looked up among the receiver's members: super.init(), Type.self, File.open(p), options.default.
A tuple's elements are read by label or by position: pair.q, pair.0, and nested, pair.0.1.
Optional chaining and unwrapping#
let city = user?.address?.city ?? "unknown"let first = array?[0]closure?()let value = cached! // traps on nonea?.b,a?[i]anda?(x)evaluate the rest of the chain only ifaholds a value; the whole chain gives an optional,noneif any link wasnone. An optional result is not doubly wrapped.a!force-unwraps: the valueaholds, or a trap onnone.
Implicit member expressions#
.Name or .Name(args) with nothing before the dot is a member of the type the context expects: a union or enum case, or a static member returning that type.
let t: Shape = .Rect(width: 3, height: 4)connect(host, timeout: .seconds(30))let p: Permissions = [.Read, .Write]When overloads compete, an implicit member fits only a parameter whose type has a member of that name — a built-in type's included — so grid[.All] is the subscript taking a union with an All case. A function type has no members, so pick(.Fast) is never the overload taking a closure. Of two members of extensions of one type that fit alike, the one whose extension fixes a type parameter (where T == F32) wins over one that constrains it (where T: Numeric).
Calls#
ArgumentList = Argument { "," Argument } [ "," ] ;Argument = [ Identifier ":" ] [ "&" | "out" | "move" ] Expression ; (* "&" marks an argument the call may write: required for an "inout" or "out" parameter ("out" may be written for an "out" one), an error anywhere else (S3209). A "T&" parameter takes the argument plainly. *)f(args) calls a function, method, closure or initialiser (Point(x: 1, y: 2)).
- Labels. A parameter with an external label is called with it:
relocate(from: a, to: b). A parameter declared with one name may be called with or without it:resize(800, 600)andresize(width: 800, height: 600)are both valid. A_label is never written. A label may be a keyword:first(where: isEven). - Defaults are evaluated at each call that leaves them off, where the declaration is.
&xpasses a place the callee may write: required for aninoutoroutparameter, an error for any other (S3209).out xmay be written for anoutparameter instead. AT¶meter takes a plain argument. What&names must be a place an assignment could write (S3010).move xas an argument moves the value into the call; see move.- Overload resolution prefers, in order: an exact match, a label match, implicit widening, protocol conformance, a generic. A label left out is a worse match than no label. Overloads that differ only in whether a closure parameter is async are told apart by the closure: one that awaits goes to the async one.
Trailing closures#
TrailingClosure = ClosureExpr { Identifier ":" ClosureExpr } ;A closure written after a call's parentheses, or after a name with no parentheses at all, is a trailing closure, passed as an argument:
items.filter { $0.isActive }withLock(mutex) { counter += 1}attempt { try fetch()} onFail: { cached()}The first trailing closure, unlabelled, goes to the first parameter the parenthesised arguments left unfilled, labelled or not, skipping one with a default whose type is not a function (Swift's forward scan). Further trailing closures carry their parameter's label, onFail:, and each starts on the line where the one before ends. Inside the parentheses an argument still needs its label.
Subscripts#
a[args] calls a subscript: an array's element, a dictionary's value (an optional), a type's own subscripts. Arguments may be labelled, grid[x: 1, y: 2].
- From the end.
^nis the positionnfrom a collection's end:xs[^1]is the last element,^0the end itself, which is never an element (xs[^0]is S3090). Out of range traps with a message saying so. - Ranges. A range subscript gives a slice:
xs[1..<4],xs[^3...],xs[..<^1]. A String's range is aSubstring. - Places. An element or a range of a
vararray is a place: it may be assigned, passed&, or have amutatingmember called on it,xs[2...].sort().
Where a collection has a read-only and a read-write subscript with the same labels, a read uses the first and a store the second. A store through a subscript that only reads, as s[^1] = c on a String, is S3010.
Closure expressions#
ClosureExpr = [ CaptureList ] ClosureSignature "=>" ( Expression | Block ) | [ CaptureList ] "{" [ ClosureHeader ] { Statement } "}" ;ClosureSignature = "(" [ ClosureParams ] ")" [ ClosureThrows ] [ "->" Type ] | Identifier ;ClosureParams = ClosureParam { "," ClosureParam } ;ClosureParam = Identifier [ ":" [ "inout" ] Type ] ;ClosureHeader = [ "(" ] ClosureParams [ ")" ] [ ClosureThrows ] [ "->" Type ] "in" ;ClosureThrows = "throws" [ "(" Type ")" ] ; (* 'rethrows' parses, and is S3664 *)CaptureList = "[" CaptureItem { "," CaptureItem } "]" ;CaptureItem = [ "weak" | "unowned" ] ( "self" | Identifier [ "=" Expression ] ) ;A closure has two spellings: an arrow form, (params) => body, and a brace form, { params in statements }.
let double = (x: Int) => x * 2let add = (a: Int, b: Int) => a + blet noop = () => { }let names = items.map(x => x.name)let ranked = items.sorted { a, b in a.score > b.score }let active = items.filter { $0.isActive }let parse = { (s: String) throws(ParseError) -> Int in try Int.parse(s) }- Parameter types may be left out where context gives them. A single untyped parameter needs no parentheses in the arrow form:
x => x + 1. Parameters may beinout, passed&xby the caller. - Implicit parameters. A brace closure with no header names its parameters
$0,$1, …; they take the parameter kinds of the expected type ($0 *= 7for an(inout Int) -> ()). - Body. An arrow body is an expression or a block; a brace body is a list of statements, and a body that is a single expression gives its value.
- Throwing. A closure throws what its body throws, unless it says
throws(E)or barethrows. Neverrethrows(S3664): a closure's type states what it throws. - Captures. A closure captures a
varby reference and aletby value. A capture list overrides:[count = localCount]captures a value under a name of the closure's own;[weak x]captures a class instance as an optional that becomesnoneonce the object is gone;[unowned x]captures it unretained, trapping if read after the object is gone;[weak x = expression]captures what the expression gives.selfmay be captured these ways too, then unwrapped withguard let self. A member reached implicitly through an un-unwrapped weakselfis an error. - Escaping. A closure passed to a parameter that is not
@escapingmay only be called or passed on to another non-escaping parameter, not stored, returned or captured by an escaping closure (S3205). Such closures cost no allocation. In amutatingmember, a non-escaping closure may changeself; an escaping one may only read it. - A closure that captures nothing is a plain function value.
- A closure that is a generator (it
yields, and its result issome Sequence<T>) is described in Declarations.
Key-path expressions#
KeyPathExpr = "\" [ Identifier [ GenericArgs ] ] "." MemberName { ( "." | "?." ) MemberName } ; (* \.address.city *)MemberName = Identifier | IntegerLiteral ;A key path is a way from a value to a part of it, as a value: a KeyPath<Root, Value> (Sable.Core). The root is written before the first dot, \Customer.address.city, or left to the context, \.address.city. Each step is a stored or computed property or a tuple element; ?. steps through an optional and makes the path's value optional.
let city: KeyPath<Customer, String> = \.address.citylet billing = \Customer.billing?.city // KeyPath<Customer, String?>print(city.value(of: customer))print(city.path) // address.citylet names = people.map(\.name) // where a function is wanted, it is oneKey paths read only. There are no key paths through subscripts, nor to the value itself. As an argument, a key path waits for its parameter's type as a closure does and settles type parameters: field(\.email) for fn field<V>(_ path: KeyPath<T, V>).
Metatype expressions#
CalledType = "[" Type ":" Type "]" (* [String: Int]() *) | PostfixType "[" ">" ".." [ "<" ] "]" ; (* Int[>..]() *)T.self is the type T as a value, of type T.Type. Any type may be written this way, not only a name: Int?.self, Point[].self, (Int, String).self, (any Named).self. A compound type is read in expression position only when .self follows it, or, for a dictionary or growable array type, when it is called — so xs[0] stays a subscript and p?.x an optional chain.
- A metatype reaches the type's static members:
type.zero()fortype: T.Type. type(of: x)is the dynamic type of a value as aType: an object's own class, what an existential holds, any other value's static type.- Metatypes compare with
==and!=. ATypeanswersname,kind,size,alignment,stride, its fields and type arguments,isInstance(_:)andisSubtype(of:). - A
Typepassed where a generic function takesT.Typeopens it:Tis the type it holds at run time. Stack.self, a generic type without arguments, is aGenericType, which caninstantiatethe type of given arguments.
Cast and type-test expressions#
CastExpr = UnaryExpr { CastOp Type } ;CastOp = "as" | "as" "?" | "as" "!" | "unchecked" "as" | "is" ;| Expression | Meaning |
|---|---|
x as T |
A conversion that always succeeds: numeric conversion (trapping if the value does not fit), upcast, existential erasure, array kind conversion, enum case to or from its integer |
x as? T |
Downcast or conformance cast, giving a T? |
x as! T |
Downcast, trapping on failure |
x unchecked as T |
Numeric conversion that never traps: integers keep their low bits; floats go toward zero and stop at the target's bounds (NaN gives 0) |
x is T |
Whether x is a T; narrows x in the code it guards |
On an optional, is, as? and as! ask about the value it holds: none is no T, and as! of it traps. A cast that could never succeed — between unrelated types, or classes on different branches — is an error (S3066). The type after a cast is never a run-time Type value (S3098); use t.isInstance(x). Casts bind as postfix operators (see the precedence table).
Try expressions#
TryExpr = ( "try" | "try" "?" | "try" "!" ) UnaryExpr [ "catch" ( Block | Expression ) ] ; (* the catch supplies an inline fallback value; '!' is try's only with nothing between them: 'try !f()' is 'try (!f())' *)A call that may throw must be marked with try (S3032 otherwise). One try covers every throwing call in the expression to its right, short of an assignment.
| Form | On error |
|---|---|
try e |
The error propagates to the enclosing function or do, converted through From if its type differs |
try? e |
The result is none; the expression's type is T? |
try! e |
Traps |
try e catch { … } |
The block's value is used instead; error is bound in it |
try e catch fallback |
The expression fallback is used instead |
let text = try read("a.txt")let maybe = try? read("b.txt")let config = try! read("defaults.toml")let fallback = try read("c.txt") catch { "" }Await expressions#
await e waits for an async call — or for an async let binding, a call into an actor from outside, or a read of an actor's state — and may suspend the current task. It is required wherever a suspension can happen. It is a prefix operator, so try await f() is written in that order. See Concurrency.
Move#
move x moves the value out of the binding x, even when its type is copyable: no copy is made, and x may not be used afterwards (it is uninitialised until assigned again). It is how ownership is handed on without a copy:
let other = move textpool.giveBack(move bytes)Values of @noncopy types are always moved, with or without the keyword.
References: the & prefix#
Outside a call's argument list, &place makes a reference value, a T&, to the place:
let first = &bag.items[0] // an Item&first.count += 1 // writes through: bag is a varA reference writes when its place may be written (a var, an inout parameter, self in a mutating member, a field or element of one); otherwise it only reads, and a write through it is S3010. While the reference is in use, any other use of its root is S3062; it may not outlive the root (S3061); and a reference into an object's or a global's array must be used where it is made (S3067). See Memory and Ownership.
Conditional expressions#
if#
IfExpr = IfStatement ; (* usable in expression position when every branch yields a value *)Where a value is wanted, an if with an else is an expression: each branch's last line is its value, and all are of one type. else if chains are allowed; the final else is required.
let size = if n > 3 { "big" } else { "small" }match#
MatchExpr = MatchStatement ; (* usable in expression position *)A match is an expression where a value is wanted: each arm's body is its value. It must be exhaustive. Its arms are described in Statements and its patterns in Patterns.
let area = match shape { case .Circle(let r) => Pi * r * r case .Rect(let w, let h) => w * h case .Empty => 0}An arm's body may also be return, break or continue, or a throw expression, which leave and give the match no value.
Throw expressions#
throw e is also an expression, wherever a value is wanted. It never gives one: its type is Never, which converts to any type. It takes the whole expression after it.
let port = configured ?? throw ConfigError.Missing("port")let n = match fit { case .One(let v) => v case _ => throw .Ambiguous(self)}Braces: record literal, trailing closure or body#
Three constructs open with {. The parser decides between them by this rule:
- Where a brace would open a statement body — after an
if,guardorwhilecondition, aforsequence, amatchorswitchsubject — a brace is always the body. Parentheses and brackets lift this, soif contains(Point { x: 1, y: 2 }) { … }reads as intended. - After a name (
Point {,Geo.Point {), the contents decide:{ }or{ identifier: …is a record literal; anything else is a trailing closure. - Anywhere else, a brace after an expression is a trailing closure.
A brace directly after a property's initialiser opens an accessor block when its first token is get, set, willSet or didSet. Rule 2 is why record literals have no field shorthand.
Inside a match arm's where clause, identifier => at the end is the arm's arrow, not a one-parameter closure: case .Busy(let t) where t > limit => retry(). Parenthesise a closure wanted there.