Contents Open

DocsLanguage Guide

Control Flow

if and guard, loops, labels, defer and using, and switch.

Control flow statements decide which code runs and how many times. Sable has the ones you know from Swift and C#: if and guard to choose, while, repeat-while and for-in to repeat, break and continue to leave or skip ahead, and return and throw to leave a function. It adds defer and using for work that must happen as a scope ends.

Sable also has a switch statement, but for most branching on a value you will use match, which binds patterns and is checked for exhaustiveness. It has a chapter of its own, Pattern Matching; this chapter shows switch only for the C-shaped dispatch it exists for.

Braces and Lines#

Every body in Sable is a block in braces, even a body of one statement: there is no if (x) doThing(); form. The condition is written without parentheses.

The opening brace must be on the same line as the statement that owns it. This is Go's rule rather than Swift's, and Sable rejects the Allman style of putting { on its own line, because a brace that starts a line could also be read as a trailing closure (see Closures). The compiler tells you when you do it.

Sable
if ready {          // the brace on the header's line    start()}

A related rule: return, break, continue, throw and fallthrough end at the end of their line, so a value they take must be on the same line. return alone on a line returns nothing, even if an expression follows on the next line.

Conditional Statements#

if#

The if statement runs its body when a condition is true. The condition must be a Bool; Sable does not treat numbers, optionals or strings as true or false.

Sable
let temperature = 31if temperature > 30 {    print("It's hot. Drink some water.")}

An else clause gives a body for when the condition is false, and else if chains further conditions, tried in order:

Sable
if temperature > 30 {    print("hot")} else if temperature < 5 {    print("cold")} else {    print("mild")}

else may start the next line after a }; it continues the statement.

if as an Expression#

Where a value is wanted, an if with an else gives one: the value of each branch's last line. Every branch must give the same type.

Sable
let size = if count > 3 { "big" } else { "small" }let shipping = if total >= 50.0 {    0.0} else if express {    9.95} else {    4.95}

This replaces the ternary operator where the choice is more than a few tokens long; cond ? a : b still exists for short ones. An if without an else cannot give a value, since it might give none.

Optional Binding: if let#

if let tests whether an optional holds a value, and if it does, binds the value to a new constant for the body:

Sable
if let user = findUser(id) {    print("found \(user.name)")} else {    print("no user \(id)")}

When the new name would be the same as the optional's, write it once:

Sable
let nickname: String? = lookupNickname(id)if let nickname {    print("hello, \(nickname)")      // 'nickname' is a String here}

Several conditions can be written after one if, separated by commas. They are checked left to right, each may use the names the ones before it bound, and the body runs only if all of them hold:

Sable
if let a = first, let b = second, a.id == b.id {    print("the same record")}

Optionals and binding are covered in depth in Optionals.

if case#

if case tests a value against a single pattern, binding what the pattern names:

Sable
if case .Circle(let radius) = shape {    print("a circle of radius \(radius)")}

This is a short form of a match with one interesting case; the patterns you can write are listed in Pattern Matching.

Conditions and Braces#

In a condition, a brace always opens the body. So a record literal in a condition, if p == Point { x: 0, y: 0 } { }, does not read the way you hope: the first brace opens the body. Put such an expression in parentheses, which lift the rule: if p == (Point { x: 0, y: 0 }) { }. The same holds for guard and while conditions, the sequence of a for, and the subject of a match.

Early Exit with guard#

A guard states what must be true for the rest of the code to make sense. If its condition fails, its else body runs, and that body must leave the scope: by return, throw, break or continue, or by calling a function that never returns.

Sable
fn ship(_ orderId: Int) throws(ShopError) -> Receipt {    guard let order = findOrder(orderId) else {        throw .NotFound(orderId)    }    guard order.isPaid else {        return Receipt.unpaid(order)    }    // 'order' is bound here, for the rest of the function    return dispatch(order)}

The names a guard let binds stay in scope after the guard, which is the point: the happy path continues at the left margin instead of nesting deeper with each check. guard case works the same way with a pattern:

Sable
guard case .Verified(let certificate) = trust else {    return}print(certificate.subject)

Loops#

while#

A while loop runs its body as long as its condition is true, checking before each pass:

Sable
var remaining = 3while remaining > 0 {    print(remaining)    remaining -= 1}

while let keeps going as long as an optional holds a value, binding it each time. It suits reading until the end of something:

Sable
while let line = reader.readLine() {    process(line)}

And while case loops as long as a value matches a pattern.

repeat-while#

repeat-while checks its condition after each pass, so the body always runs at least once. It is Swift's spelling of C's do-while:

Sable
var attempts = 0repeat {    attempts += 1} while !connect() && attempts < 3

The while must follow the closing brace on the same line, } while …; a while on a line of its own starts a new loop.

for-in#

A for-in loop goes through a sequence: a range, an array, a string, a dictionary, or anything else that is a Sequence.

Sable
for i in 0..<3 {    print(i)                   // 0, 1, 2}for i in 1...3 {    print(i)                   // 1, 2, 3: an inclusive range}for name in ["ann", "bob"] {    print("hello, \(name)")}

If you don't need each value, write _ in its place:

Sable
var power = 1for _ in 0..<10 {    power *= 2}print(power)                   // 1024

A dictionary gives its key-value pairs, which you take apart in the loop, and an array's enumerated() gives each element with its offset:

Sable
for (product, count) in stock {    print("\(product): \(count)")}for (i, step) in steps.enumerated() {    print("\(i + 1). \(step)")}

To count in steps other than one, use stride(from:to:by:), which stops before the end, or stride(from:through:by:), which includes it if a step lands on it. A range's step(by:) is the same thing:

Sable
for minute in stride(from: 0, to: 60, by: 15) {    print(minute)              // 0, 15, 30, 45}for tick in (0..<10).step(by: 3) {    print(tick)                // 0, 3, 6, 9}for n in (1...3).reversed() {    print(n)                   // 3, 2, 1}

A for over a range or a stride compiles to a counting loop; nothing is allocated.

Filtering with where#

A where clause after the sequence skips the elements that don't satisfy it:

Sable
for item in inventory where item.isActive {    restock(item)}

for try and for await#

Some sequences can fail as you go through them, such as the lines of a file being read. A loop over one is written for try, and leaves with the error as a try would. Writing for alone over such a sequence is an error (S3032). Arrays, ranges and the other sequences that cannot fail never need it.

Sable
import Sable.IOfor try line in try File.lines("orders.csv") {    print(line)}

Here the first try is the loop's, for reading each line; the second is for the call to File.lines, which can fail before any line is read, when the file cannot be opened.

Likewise for await goes through an asynchronous sequence, waiting for each element. Both are covered properly in Error Handling and Concurrency.

Control Transfer Statements#

break and continue#

break ends the innermost loop at once. continue ends only the current pass, and goes on with the next one:

Sable
for n in readings {    if n < 0 {        continue               // skip bad readings    }    if n > limit {        break                  // stop at the first reading over the limit    }    record(n)}

Labelled Statements#

With nested loops, a plain break or continue acts on the innermost one. To act on an outer loop, give it a label, a name and a colon before the loop, and name the label after break or continue:

Sable
var found = 0outer: for row in rows {    for col in cols {        if row == col {            found += 1            continue outer     // the next row        }        if row < 0 {            break outer        // leave both loops        }    }}

Deferred Actions#

defer#

A defer block runs when the scope it is in is left, however it is left: at the end of the block, at a return, at a break or continue, or when an error is thrown. Use it to keep clean-up next to the code that made it necessary:

Sable
import Sable.IOfn exportReport(_ path: String, _ rows: U8[:][:]) throws(IoError) {    let file = try File.open(path, options: .writing)    defer { file.close() }    for row in rows {        try file.write(row)     // if this throws, the file is still closed    }}

Several defers in one scope run in reverse order of how they were written, last first, which undoes things in the opposite order to how they were done:

Sable
fn demo() {    defer { print("first defer") }    defer { print("second defer") }    print("body")}demo()
bodysecond deferfirst defer

Sable compiles errors to an ordinary return value, not to unwinding, so a defer on the throwing path is simply code on that path; it costs nothing when nothing is thrown.

using#

For a resource that is a move-only (@noncopy) value, such as a file handle or a pooled connection, using declares a binding that is released at the end of the enclosing block:

Sable
fn transfer() throws(DbError) {    using let conn = pool.acquire()    using var tx = conn.begin()    try tx.execute(debit)    try tx.execute(credit)    // tx, then conn, are released here, in reverse order}

It is like writing a defer that destroys the value, with one difference: the binding is consumed as the scope ends, so the compiler rejects any use after release. Releasing means destroying the value, which runs its deinit; there is no Disposable protocol to implement. Move-only types and deinit are covered in Memory and Ownership.

using has no braced form. using let f = open(p) { … } would be read as a call to open with a trailing closure, so a using binding always lasts to the end of the block it is in. To release it sooner, put it in a block of its own:

Sable
do {    using let lock = mutex.acquire()    counter += 1}                               // released here

switch#

switch is for C-shaped dispatch on integers and enums, where you want explicit fallthrough. It compares the subject with each case's values in order, and runs the first case that is equal. default, wherever it is written, runs when none is.

Sable
switch statusCode {    case 200, 201:        handleOk()    case 301:        fallthrough    case 302:        redirect()    default:        fail()}

A case ends where the next one begins, so there is no accidental fall-through and no need for C#'s break at the end of each case. fallthrough goes on into the case written after it; break leaves the switch early; continue, inside a loop, goes on with the loop around it.

switch does not bind patterns. For anything beyond comparing values, use match, which is both a statement and an expression and checks that every case is handled:

Sable
let label = match statusCode {    case 200, 201 => "ok"    case 300...399 => "redirect"    case let code where code >= 500 => "server error \(code)"    default => "other"}

Everything about match is in Pattern Matching.

Leaving a Function#

return leaves the current function, with a value if the function has a result type. throw leaves it with an error, as described in Error Handling. throw can also be used as an expression where a value is wanted, since it never gives one:

Sable
let port = configured ?? throw ConfigError.Missing("port")

A function whose result type is Never does not return at all; calling one counts as leaving the scope, which is why it may end a guard's else.

Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.