Menu
Coddy logo textTech

Methods and self

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

Inside a method, self is the instance the method was called on. self.count and count mean the same property, so self is usually left out:

class Counter {
    var count = 0
    func increment() {
        self.count += 1
    }
}

let c = Counter()
c.increment()
print(c.count)

Output:

1

self is needed when a parameter has the same name as a property. Then the plain name means the parameter and self.name means the property:

class Player {
    var name = "unknown"
    func rename(name: String) {
        self.name = name
    }
}

let p = Player()
p.rename(name: "Ada")
print(p.name)

Output:

Ada

Methods can call other methods of the same instance, which keeps each method small:

class Cart {
    var total = 0
    func add(_ price: Int) {
        total += price
    }
    func addTwice(_ price: Int) {
        add(price)
        add(price)
    }
}

let cart = Cart()
cart.addTwice(5)
print(cart.total)

Output:

10

A method can also return a value computed from the properties. Here isEmpty() answers a question about the instance without changing it:

class Cart {
    var items: [String] = []
    func add(_ item: String) {
        items.append(item)
    }
    func isEmpty() -> Bool {
        items.count == 0
    }
}

let cart = Cart()
print(cart.isEmpty())
cart.add("tea")
print(cart.isEmpty())

Output:

true
false
challenge icon

Challenge

Easy

Complete the class Thermostat. setTarget(target:) stores the parameter in the property target (use self), warmer() raises the target by 1, and display() returns target: 21.

The supplied code reads a starting target and a list of commands (warmer or set <n>), applies them and prints display() at the end.

Your code goes in Thermostat.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 t = Thermostat()
t.setTarget(target: Int(input[0])!)
for cmd in input.dropFirst() {
    if cmd == "warmer" { t.warmer() } else { t.setTarget(target: Int(cmd.dropFirst(4))!) }
}
print(t.display())
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