DocsLanguage Guide
Optionals
none, optional binding, chaining, defaults, force-unwrapping and narrowing.
An optional is a value that may be missing. A lookup that finds nothing, a field not filled in yet, a parse that failed: Sable writes each of these as an optional type, T?, which either holds a T or holds nothing, written none.
A plain T can never be none. There's no null reference hiding in every class type, as in C# or Java, and no separate nullability analysis that only warns: if a value may be missing, its type says so, and Sable makes you deal with the missing case before you use the value. The Basics introduced optionals briefly; this chapter covers all the ways to make, test, unwrap and pass them on.
Optional types#
Write ? after any type to make its optional. A function that may not find what it's asked for returns one:
struct User { var id: Int var name: String var email: String?}fn findUser(_ id: Int, in users: User[]) -> User? { for user in users { if user.id == id { return user } } return none}none is the literal for "nothing here". It is only valid where an optional is expected:
var nickname: String? = nonenickname = "Ada"An optional is not its value. You can't read email.count, pass a String? where a String is wanted, or do arithmetic on an Int?:
let count: Int? = 3let doubled = count * 2 // error[S3009]: '*' cannot take an 'Int?'let user = User { id: 1, name: "Ada", email: none }print(user.email.count) // error[S3011]: 'user.email' may hold nothingThe rest of this chapter is about the ways to get from a T? to a T safely.
What an optional is#
T? is shorthand for Optional<T>, a union defined in the standard library:
@frozen union Optional<T> { Some(T), None }So .Some(x) and .None are valid spellings, and you'll see them in patterns. In ordinary code, write none rather than .None, and let the compiler wrap values for you rather than writing .Some(x).
Optionals nest: an Int?? is an optional of an optional, and is not the same type as Int? (S3004).
Implicit promotion#
A T converts to a T? automatically wherever an optional is wanted: on assignment, as an argument, as a returned value, and as an element of an array literal. That's why findUser above can return user without writing .Some(user):
fn parsePort(_ text: String) -> Int? { if text == "default" { return 443 // promoted to Int? } return text.toInt() // already an Int?}var limit: Int? = 10 // promotedlet ports: Int?[] = [80, none, 8080]This is the only direction it works in. Going back from T? to T always takes one of the forms below.
Optional binding#
if let tests whether an optional holds a value and, if it does, binds the value to a new constant of the plain type:
let input = "8080"if let port = input.toInt() { print("listening on \(port)") // port is an Int here} else { print("'\(input)' is not a number")}// prints listening on 8080if var binds a variable instead, which you may change inside the body (the change does not reach the optional).
When the name you want is the optional's own name, leave out the = …: if let email means if let email = email, and shadows the optional with its value inside the body:
fn contact(_ user: User) -> String { if let email = user.email { return email } return "no address for \(user.name)"}fn notify(_ email: String?) { if let email { print("sending to \(email)") }}Several conditions#
An if may bind several optionals and test ordinary conditions, separated by commas. The body runs only if every binding succeeds and every condition is true; each one may use the names bound before it:
if let user = findUser(3, in: users), let email = user.email, email.hasSuffix("@example.com") { print("\(user.name) is staff")}Taking tuples apart#
When the optional holds a tuple, the binding may destructure it:
fn lookup(_ key: String) -> (Int, String)? { return key == "a" ? (1, "alpha") : none}if let (n, word) = lookup("a") { print("\(n) is \(word)")}// prints 1 is alphaguard let#
guard let is the early-exit form. If the optional holds nothing, the else block runs and must leave the scope — by return, throw, break or continue. If it holds a value, the binding stays in scope for the rest of the function:
fn sendWelcome(to id: Int, in users: User[]) -> Bool { guard let user = findUser(id, in: users) else { return false } guard let email = user.email else { print("\(user.name) has no email") return false } print("welcome mail to \(email)") return true}This keeps the main path of a function unindented, with each failure handled where it's detected. The shorthand works here too: guard let email else { … }.
A common use is in a closure that captured self weakly (see Closures). A weak capture is optional, so the closure unwraps it first, usually under the same name:
let refresh = [weak self] () => { guard let self else { return } self.reload()}Optional chaining#
To reach a member of what an optional holds, use ?. instead of .. If the optional holds a value, the member is read; if it holds nothing, the whole expression is none. Either way the result is optional:
let user: User? = findUser(3, in: users)let length: Int? = user?.name.countHere user?.name.count reads name and its count only if there is a user. Note that only one ?. is needed: once a chain has gone through an optional, the rest of it is skipped when that optional is empty.
When a member along the chain is itself optional, write ?. again after it. The result is still a single optional, not an optional of an optional:
struct Address { var city: String }struct Customer { var address: Address? }fn city(of customer: Customer?) -> String? { return customer?.address?.city}?. reaches what the optional holds. To reach the optional's own members (such as map, described below), use a plain ..
Through subscripts and calls#
The same works for subscripts, written ?[…], and for calling an optional function value, written ?(…):
let scores: Int[]? = [90, 85]let first = scores?[0] // Int?var onChange: ((Int) -> Void)? = noneonChange?(42) // does nothing while onChange is noneAssigning through a chain#
A chain may be the target of an assignment. The assignment happens only if every optional along the way holds a value; otherwise nothing is stored:
class Node { var value: Int = 0 var next: Node? = none}let head = Node()head.next?.value = 9 // no next node yet: nothing happenshead.next = Node()head.next?.value = 9 // stores 9The assigned value must have the member's type, and the member must be assignable.
Default values with ??#
The nil-coalescing operator a ?? b gives what a holds, or b if a holds nothing. With a plain b, the result is plain too, so ?? is the shortest way out of an optional:
let city = customer?.address?.city ?? "unknown"let port = parsePort(text) ?? 443b is evaluated only when it's needed, so it may be an expensive call. Its type must match what a holds (S3004), and a must be an optional (S3011).
When b is also an optional, the result is optional: cached ?? fetched is cached if it holds a value and otherwise fetched, whatever that holds. Chaining several gives the first that holds one:
let fromCache: String? = nonelet fromDisk: String? = "settings"let found = fromCache ?? fromDisk // String?, holds "settings"let chosen = fromCache ?? fromDisk ?? "defaults" // StringBecause throw is an expression of type Never, the right-hand side may also be a throw, which turns a missing value into an error: let port = configured ?? throw ConfigError.Missing("port"). Error Handling covers this.
??=#
a ??= b assigns b to the optional variable a, but only if a currently holds nothing. It's how a value is filled in once:
var displayName: String? = nonedisplayName ??= "Guest"displayName ??= "Someone else" // already holds a value: unchangedprint(displayName ?? "")// prints GuestForce unwrapping#
value! asserts that an optional holds a value and gives that value. If it holds nothing, the program stops with a trap:
let digits = "42".toInt()! // an Int; traps if the text weren't a numberUse ! only where a missing value means the program itself is wrong, never as a quick way past the compiler. Where you can say why the value must be there, prefer expect, which takes a message and reports it, with your line, when it fails:
let port = "8080".toInt().expect("the port is a number")Applying ! to something that isn't optional is an error (S3011). ! binds as tightly as ., so a.b!.c unwraps a.b and reads its c.
Optionals in patterns#
Since an optional is a union, match takes it apart like any other. The pattern let v? matches an optional that holds a value and binds it; none matches an empty one. Together they're exhaustive:
fn label(_ count: Int?) -> String { return match count { case 0? => "none yet" case let n? where n > 99 => "99+" case let n? => "\(n)" case none => "unknown" }}let v? is shorthand for .Some(let v), and 0? for .Some(0). if case let v? = x works as if let v = x does. Pattern Matching has the details.
Optionals and structural unions#
An optional is also the structural union of its type with None: Int? and Int | None are the same type, and a structural union with None among its cases, such as Int | String | None, is an optional of Int | String. Unions normalise, so Int | Int? is just Int?.
For such a union, comparing with none narrows it, the way an is test narrows a structural union:
fn width(_ value: Int | String | None) -> Int { if value != none { let present: Int | String = value // narrowed: none is ruled out return match present { case let n as Int => n case let s as String => s.count } } return 0}For a plain T?, if let is the clearer way to get the value out, since it also gives you a name for it.
Casting optionals#
is, as? and as!, and the patterns is T and let x as T, look through an optional and ask about the value it holds. An optional holding nothing is no T: is is false for it, as? gives none, and as! traps.
open class Animal { }class Dog: Animal { fn fetch() { print("fetching") }}let pet: Animal? = Dog()if let dog = pet as? Dog { // asks of the Dog it holds dog.fetch()}let nothing: Animal? = noneprint(nothing is Dog)// prints falseAn optional of a subclass converts to an optional of its superclass, Dog? to Animal?, with none staying none. Casting in general is covered in Casting, Metatypes and Reflection.
Optional's own members#
Optional has methods of its own, reached with . on the optional itself. They're useful at the end of a chain, where if let would need a statement:
| Member | Gives |
|---|---|
isSome, isNone |
whether it holds a value, or nothing |
map(f) |
f of what it holds, as an optional; none when empty |
flatMap(f) |
the same, for an f that itself gives an optional |
filter(p) |
what it holds if p is true of it, otherwise none |
unwrap(or: x) |
what it holds, or x, as ?? does |
unwrap(orElse: f) |
what it holds, or what f makes, calling f only then |
expect(message) |
what it holds; traps with the message when empty |
take() |
what it held, leaving none in its place (mutating) |
replace(with: x) |
what it held, putting x in its place (mutating) |
zip(other) |
both values as a tuple when both hold one |
okOr(error) |
an Outcome: .Ok of the value, or .Err(error) |
let raw: String? = "42"let parsed = raw.flatMap({ t in t.toInt() }).map({ n in n * 2 })print(parsed ?? 0)// prints 84var pending: Int? = 5let job = pending.take() // job holds 5, pending is noneAn optional is Equatable, Hashable, Comparable and Debug when what it holds is. Two optionals are equal when both are none or both hold equal values, and none orders before every value.
Implicitly unwrapped optionals#
T! is an optional that is unwrapped automatically wherever a plain T is used, trapping if it holds nothing. It is still an optional — you can bind it with if let, compare it with none and use ?? on it — and diagnostics show it as written, Int!.
let handle: Int! = 3print(handle + 1)// prints 4T! exists for interop, where a C API returns a pointer that is documented never to be null but whose type can't say so. Don't use it in ordinary Sable code: it moves the check from compile time to run time, which is what optionals exist to avoid.
How optionals are stored#
An optional costs little or nothing. Sable stores the "is it there?" bit in space the value doesn't use wherever it can, a technique called spare-bit packing. For a class reference, which can never be null, T? is exactly one pointer, with none stored as the null pointer — the same size and representation as a nullable reference in C or C#. The same applies to references (T&?). For other types the optional uses bit patterns the value can never have, such as a Bool's unused bits, and only needs extra room for its tag when there are none.
So prefer T? over sentinel values like -1 or an empty string: it says what you mean, the compiler checks every use, and it usually costs no more.