Thuta Learning
AdvancedProgrammingbeginner

Methods

Relax. We'll talk through this in plain words — no textbook voice.

Methods are functions tied to a particular type. Functions can stand alone, but methods describe the behavior of a struct/class/enum instance.

swift
class Counter {
    var count = 0

    func increment() {
        count += 1
    }

    func increment(by amount: Int) {
        count += amount
    }

    func reset() {
        count = 0
    }
}

let counter = Counter()
counter.increment()
counter.increment(by: 5)
print(counter.count)

Counter class has count state, and its methods change that state. increment() increases it by 1, and increment(by:) increases it by the given amount.

You should see
6

Easy traps

  • If you write a method inside a struct that changes a property, you'll likely need mutating. Class methods don't need this.