DevPrep

All topics › Programming basics

Method

Junior

Essence

A method is a function bound to a type. It has an implicit self and works with the state of an instance or of the type. In Swift not only classes have methods — so do struct, enum, actor, and even protocols via extension.

Kinds of methods in Swift

struct Counter {
    private(set) var value = 0
    mutating func increment() { value += 1 }  // the method mutates a value type
    static func zero() -> Counter { Counter() }    // type method (a factory)
}

class Shape {
    class func make() -> Shape { Shape() }  // class func can be overridden
    func area() -> Double { 0 }                    // vtable dispatch
    final func describe() -> String { "area \(area())" }   // static dispatch
}

final class Circle: Shape {
    var r = 1.0
    override func area() -> Double { .pi * r * r }
}

var c = Counter.zero()
c.increment()
print(c.value)                 // 1
print(Circle().describe())     // area 3.141592653589793

Dispatch — what a middle gets asked

A method declared in a class extension is dispatched statically and cannot be overridden — a classic interview trap.

Encapsulation

Methods are the public interface to private state: private(set) var value plus increment() guarantee the counter changes only by the type's rules.

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store