DocsLanguage Guide
Initialization and Deinitialization
Initialisers, delegation, required and convenience initialisers, failing safely, and deinit.
Initialisation is preparing a new instance of a structure, class, union or enum for use: giving every stored field a value, and doing any other set-up the instance needs before anyone sees it. You write that work as initialisers, special methods called init that run when a value is made.
Sable checks initialisation statically. Every stored field must have a value on every path out of an initialiser, and a field can't be read before it has one. There is no zeroed or "default" state to fall back on. The other half of the story is deinitialisation: a class's deinit runs at the exact moment its last reference goes away, which is what makes resource cleanup in Sable deterministic.
Setting Initial Values for Stored Properties#
Every stored field must be set by the time an instance is made. There are two ways to set one: give it an initial value where it's declared, or assign it in an initialiser.
struct Fahrenheit { var temperature: F64 init() { temperature = 32.0 }}var f = Fahrenheit()print("The default temperature is \(f.temperature)° Fahrenheit")// prints The default temperature is 32.0° FahrenheitIf a field always starts out the same, an initial value says it more directly, and every initialiser starts from it:
struct Fahrenheit { var temperature = 32.0}Setting a field in an initialiser stores it directly: property observers don't run while a value is being made.
Default and Memberwise Initialisers#
You don't always have to write an initialiser.
A structure that declares no init gets a memberwise initialiser: one labelled parameter per stored field, in declaration order. A field with an initial value gives a parameter you can leave out:
struct Size { var width = 0.0, var height = 0.0}let twoByTwo = Size(width: 2.0, height: 2.0)let zeroByTwo = Size(height: 2.0)let zeroByZero = Size()The memberwise initialiser is generated only while the struct declares no initialiser of its own. As soon as you write an init, it is gone, and the initialisers you wrote are the only ones. (To keep it beside your own, Swift users move their initialisers to an extension; in Sable, a struct can always still be made with a record literal, Size { width: 2.0, height: 2.0 }, whatever initialisers it declares.)
A class gets no memberwise initialiser. A class that declares no init, and all of whose stored fields have initial values, is made with an implicit init(), which sets each field to its initial value:
class ShoppingList { var items: String[>..] = [] var purchased = false}let list = ShoppingList()Customising Initialisation#
An initialiser is written like a method named init, with no fn and no result type. It may take parameters, and those parameters have argument labels exactly as a function's do:
struct Celsius { var temperature: F64 init(fromFahrenheit fahrenheit: F64) { temperature = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: F64) { temperature = kelvin - 273.15 } init(_ celsius: F64) { temperature = celsius }}let boilingPoint = Celsius(fromFahrenheit: 212.0)let freezingPoint = Celsius(fromKelvin: 273.15)let bodyTemperature = Celsius(37.0)print(boilingPoint.temperature)// prints 100.0Labels matter more for initialisers than for methods, because every initialiser has the same name: the labels are what tell Celsius(fromFahrenheit:) from Celsius(fromKelvin:). Use _ when the argument's meaning is obvious without one, as Celsius(37.0) is.
Inside an initialiser, self.field = value and field = value both set a field; you need self. when a parameter has the field's name. A let field can be set in an initialiser, but not afterwards.
Every field must be set on every path through the initialiser. One that is set only on some paths is an error (S3028):
struct Reading { var value: F64 init(raw: F64) { if raw >= 0 { value = raw } // error: 'value' is not initialised on every path }}Initialiser Delegation#
An initialiser can hand some or all of its work to another initialiser of the same type, by calling self.init(…). This avoids writing the same set-up twice:
struct Point { var x = 0.0, var y = 0.0 }struct Size { var width = 0.0, var height = 0.0 }struct Rect { var origin = Point() var size = Size() init() { } init(origin: Point, size: Size) { self.origin = origin self.size = size } init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) }}let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0))print(centerRect.origin)// prints Point(x: 2.5, y: 2.5)An initialiser that delegates leaves the fields' initial values to the one it calls: it doesn't set them first and then have them set again.
Class Initialisation#
Classes add a superclass to the picture, whose part of the object has to be made too. Sable sorts a class's initialisers into two kinds.
Designated and convenience initialisers#
A designated initialiser is the ordinary kind: it sets the class's own fields and, in a subclass, calls a superclass initialiser to make the rest. Every initialiser you've seen so far is one.
A convenience initialiser, marked convenience init, does no initialising itself. It must delegate to another initialiser of the same class with self.init(…) (S3141). Use one for a shortcut that fills in common arguments:
open class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") }}let mystery = Food()print(mystery.name)// prints [Unnamed]A convenience init that doesn't delegate is an error, which tells you to drop the word.
Calling super.init#
A subclass's own designated initialiser must call super.init(…) on every path that returns, or else delegate across with self.init(…) (S3143). That is how the superclass's fields get their values:
class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } convenience init(name: String) { self.init(name: name, quantity: 1) }}The check is precise. Calling super.init inside an if with no else, or in only some branches of a chain, is refused, with the diagnostic saying it isn't "called on every path".
There is one exception. A superclass made with the implicit init(), one that declares no initialiser and gives all its fields initial values, may be left alone: a subclass initialiser that never calls super.init has that init() called for it.
open class Labelled { var label: String = "default"}class Tally: Labelled { var count: Int init(count: Int) { self.count = count } // Labelled's init() is called for it}A superclass that declares its own init(), however simple, must be called explicitly.
Inheriting initialisers#
A subclass that declares no init of its own, and whose own stored fields all have initial values, inherits its superclass's initialisers. Each inherited initialiser sets the subclass's fields to their initial values and then runs the superclass's:
class ShoppingItem: RecipeIngredient { var purchased = false}let eggs = ShoppingItem(name: "Eggs", quantity: 6)print("\(eggs.name) \(eggs.quantity) \(eggs.purchased)")// prints Eggs 6 falseOnce a subclass declares any initialiser, it inherits none, and its initialisers are the only ways to make it.
Required initialisers#
Write required init for an initialiser that every subclass must implement, so that code which makes instances of some subclass of a class, without knowing which, can rely on it existing.
Note
The current compiler accepts the required modifier but doesn't yet check that subclasses implement the initialiser.
Throwing, Async and Generic Initialisers#
An initialiser can do anything a function can before it finishes. It may throw, typed with throws(E) or bare throws, or be rethrows; it may be async; and it may be generic:
struct ParseError: Error { let line: Int}struct Header { var name: String var value: String init(parsing line: String) throws(ParseError) { let parts = line.split(separator: ':') guard parts.count == 2 else { throw ParseError { line: 1 } } name = parts[0].trimmed() value = parts[1].trimmed() }}struct Page { var body: String async init(loading url: String) { body = await fetch(url) }}struct Label { var text: String init<T>(describing value: T) { text = "\(value)" }}A call to a throwing initialiser is written with try, and to an async one with await, as for any function: let header = try Header(parsing: line), let page = await Page(loading: url). A protocol may require an init that throws, and a conforming type meets it with an initialiser that throws that error or nothing. Errors and try are covered in Error Handling.
When an initialiser throws part way#
An initialiser that throws has made nothing. Sable undoes exactly the work it had done:
- the fields it had already set are destroyed;
- the fields it hadn't reached are left alone, since there is nothing in them;
- no
deinitruns, because there is no object to deinitialise.
class Tracked { let name: String init(_ name: String) { self.name = name; print("made \(name)") } deinit { print("gone \(name)") }}class Connection { let socket: Tracked let session: Tracked init(failing: Bool) throws(ParseError) { socket = Tracked("socket") if failing { throw ParseError { line: 0 } } session = Tracked("session") } deinit { print("connection closed") }}do { let c = try Connection(failing: true)} catch { print("failed")}made socketgone socketfailedsocket was set, so it is destroyed; session never was; and Connection's deinit doesn't run, since no connection was ever made. For a class, the same holds whether the throw came from its own initialiser, from a superclass initialiser it called, or from one it delegated to, before or after that call: the object is let go of unmade, its fields set so far are destroyed, its memory is freed once nothing else holds it, and no deinit runs, neither its class's nor any superclass's.
Initialisers in Extensions#
An extension can add initialisers, with rules that keep a type's own initialisation in charge:
An extension of a struct, enum, union or built-in type may add an initialiser that gives
selfits value on every path, field by field, by delegating withself.init(…), or by assigningself = …(S3028):extension String { init(twice s: String) { self = s + s } } print(String(twice: "ab")) // prints ababAn extension of a class may add only a
convenience init, which hands the work to one of the class's own initialisers withself.init(…)(S3141). A designated initialiser in a class extension is an error (S3030), as is any stored property. Initialisers a class gains this way aren't inherited by subclasses.An extension of a protocol can't add an initialiser; a static function does the same job.
Constant Initialisers#
An initialiser marked const init can run while your program is being compiled, so its result can be the value of a const:
final class Box { let n: Int const init(_ n: Int) { self.n = n }}const Three = Box(3)What a const init may do, and the rest of compile-time evaluation, is covered in Compile-Time Evaluation.
Deinitialisation#
A deinitialiser runs just before an instance is destroyed. You write one with deinit, which takes no parameters and no parentheses. Classes can have one, and so can @noncopy structs, which are move-only and so have exactly one owner (see Memory and Ownership):
@noncopy struct FileGuard { let path: String deinit { print("closing \(path)") }}do { let file = FileGuard(path: "log.txt") print("writing \(file.path)")}print("done")writing log.txtclosing log.txtdoneDeterministic destruction#
deinit runs at the moment the last strong reference goes away, not at some later collection. This is a feature you can build on: a file closes when the object that owns it is released, and a lock unlocks when its guard goes out of scope, with no defer and no Dispose. (using, in Control Flow, relies on exactly this.)
The order is fixed too:
- A subclass's
deinitruns first, then its superclass's, up the chain. Each can still use every field. - Then the fields are released, in the reverse of the order they're declared.
open class Vehicle { var name: String init(name: String) { self.name = name } deinit { print("vehicle \(name) deinit") }}class Bicycle: Vehicle { deinit { print("bicycle deinit") }}do { let bike = Bicycle(name: "bmx")}// prints bicycle deinit// prints vehicle bmx deinitA deinit never runs for an object whose initialiser threw, as described above: such an object was never made.