Method
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
- Instance methods — called on an object/value:
user.rename(...). mutating— forstruct/enum: the method changesself; it cannot be called on aletvalue.- Type methods:
static func— cannot be overridden;class func— can be overridden in a subclass. They often act as factories (Date.now;URL(string:)is an initialiser,UIColor.systemBlueis a type property). - Initialisers and
deinit— special methods. - Methods in protocols and extensions — default behaviour that needs no inheritance.
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
- Static —
struct,enum,final,private, methods in anextension: the address is known at compile time, the fastest option, can be inlined. - Vtable — regular class methods: a lookup in the virtual method table.
- Witness table — a call through
any Protocol/ a generic. - Message —
@objc dynamic:objc_msgSend, selector lookup at run time; needed for KVO and method swizzling.
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.