Menu
Coddy logo textTech

Initializers

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 4 of 57.

An initializer, written init, runs when an instance is created and gives the properties their starting values. Its parameters become the arguments of the type call:

class Book {
    var title: String
    var pages: Int

    init(title: String, pages: Int) {
        self.title = title
        self.pages = pages
    }
}

let book = Book(title: "Dune", pages: 412)
print(book.title)
print(book.pages)

Output:

Dune
412

Every property needs a value before the instance can be used. A property without a default value must be set in init, or the class does not compile. A property declared with let can be set once in init and never changed afterwards:

class Book {
    let isbn: String     // set once, in init
    var title: String

    init(isbn: String, title: String) {
        self.isbn = isbn
        self.title = title
    }
}

Parameters of init can have default values, so callers give only what differs:

class Timer {
    var seconds: Int
    var label: String

    init(seconds: Int, label: String = "timer") {
        self.seconds = seconds
        self.label = label
    }
}

let egg = Timer(seconds: 300, label: "egg")
let quick = Timer(seconds: 30)
print("\(egg.label) \(egg.seconds)")
print("\(quick.label) \(quick.seconds)")

Output:

egg 300
timer 30

A class can have more than one initializer, each with different parameters. A convenience init fills in some values and calls the main one with self.init(...):

class Temperature {
    var celsius: Double

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

    convenience init(fahrenheit: Double) {
        self.init(celsius: (fahrenheit - 32) * 5 / 9)
    }
}

print(Temperature(celsius: 20).celsius)
print(Temperature(fahrenheit: 212).celsius)

Output:

20.0
100.0
challenge icon

Challenge

Easy

Write the initializer of the class Account. It takes owner and an optional balance that defaults to 0, and stores both. Then complete summary(), which returns Ada has 150.

The supplied code reads an owner and, when a second line is present, a starting balance. It creates the account with or without the balance and prints summary().

Your code goes in Account.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let account = input.count > 1 ? Account(owner: input[0], balance: Int(input[1])!) : Account(owner: input[0])
print(account.summary())
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground