TExcelTAD
Home › Swift › Swift Initializers

Swift Initializers

An initializer (init) prepares a new instance for use. Swift has one strict rule: every stored property must have a value before the instance can be used. Initializers are where you guarantee that. This lesson covers custom, overloaded, failable and convenience initializers.

A custom initializer

Write init like a method without func and without a return type. Use self. to tell a property apart from a parameter with the same name.

swift · try it yourself
struct Temperature {
    let celsius: Double

    init(celsius: Double) {
        self.celsius = celsius
    }

    init(fahrenheit: Double) {
        celsius = (fahrenheit - 32) * 5 / 9
    }

    init(kelvin: Double) {
        self.init(celsius: kelvin - 273.15)   // delegate to another init
    }
}

let a = Temperature(celsius: 21)
let b = Temperature(fahrenheit: 212)
let c = Temperature(kelvin: 273.15)
print(a.celsius, b.celsius, c.celsius)
21.0 100.0 0.0

A type can have several initializers as long as their argument labels or types differ. A let property may be assigned once inside an initializer.

Note: In a struct, writing your own init inside the struct body removes the free memberwise initializer. If you want to keep it, put your custom initializers in an extension instead.

Failable initializers: init?

Sometimes the input is invalid and no instance should be created. A failable initializer is written init? and returns nil on failure, so the result is an optional.

swift · try it yourself
struct Email {
    let address: String

    init?(_ text: String) {
        guard text.contains("@"), !text.hasPrefix("@") else {
            return nil
        }
        address = text.lowercased()
    }
}

for input in ["Linh@Example.com", "not-an-email", "@oops"] {
    if let email = Email(input) {
        print("valid:", email.address)
    } else {
        print("invalid:", input)
    }
}
valid: linh@example.com
invalid: not-an-email
invalid: @oops

You already met failable initializers from the standard library: Int("42") returns Int? and Planet(rawValue: 3) returns Planet?.

Class initializers: designated and convenience

Classes don't get a memberwise initializer, and inheritance makes initialization more involved. Swift distinguishes two kinds:

Kind Syntax Rule
Designated init(...) Fully initializes all properties introduced by this class, then calls a superclass designated init
Convenience convenience init(...) Must call another initializer of the same class (self.init)
swift · try it yourself
class Window {
    let title: String
    var width: Int
    var height: Int

    // designated initializer
    init(title: String, width: Int, height: Int) {
        self.title = title
        self.width = width
        self.height = height
    }

    // convenience initializer: a shortcut with sensible defaults
    convenience init(squareTitled title: String, side: Int = 300) {
        self.init(title: title, width: side, height: side)
    }

    func describe() -> String { "\(title) \(width)x\(height)" }
}

print(Window(title: "Editor", width: 800, height: 600).describe())
print(Window(squareTitled: "Palette").describe())
print(Window(squareTitled: "Preview", side: 120).describe())
Editor 800x600
Palette 300x300
Preview 120x120

Initializers and inheritance

A subclass's designated initializer must set its own new properties first, then call super.init(...). Only after that may it use self or change inherited properties. This is called two-phase initialization.

swift · try it yourself
class Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
        print("Vehicle init")
    }
}

class Bike: Vehicle {
    var hasBell: Bool

    init(hasBell: Bool) {
        self.hasBell = hasBell        // phase 1: own properties
        super.init(wheels: 2)         // then the superclass
        print("Bike init, bell: \(self.hasBell)")  // phase 2: self is ready
    }
}

let bike = Bike(hasBell: true)
print(bike.wheels)
Vehicle init
Bike init, bell: true
2

If you forget to initialize a property, the compiler refuses the code:

swift · try it yourself
class User {
    let name: String
    var age: Int

    init(name: String) {
        self.name = name
    }
}
<source>:7:5: error: return from initializer without initializing all stored properties
1 | class User {
2 |     let name: String
3 |     var age: Int
  |         `- note: 'self.age' not initialized
4 |
5 |     init(name: String) {
6 |         self.name = name
7 |     }
  |     `- error: return from initializer without initializing all stored properties
8 | }

Required initializers

Marking an initializer required forces every subclass to provide it. You will see this in protocols and in UIKit (required init?(coder:)).

swift
class Shape {
    required init() {}
}

class Circle: Shape {
    required init() {   // must be implemented by every subclass
        super.init()
    }
}

Tip: Give properties default values where it makes sense (var count = 0). Fewer things to set in init means fewer chances to forget one.

Test yourself

What does a failable initializer init? return when it fails?

  1. An empty instance
  2. nil
  3. It throws an error
  4. false

What must a convenience init do?

  1. Call super.init directly
  2. Call another initializer of the same class with self.init
  3. Initialize every property itself
  4. Be marked required

In a subclass designated initializer, what comes first?

  1. super.init(...)
  2. Calling methods on self
  3. Initializing the subclass's own new properties
  4. Nothing — order does not matter