Understanding Method Dispatch in Swift

class vs. struct

Steven Curtis
3 min readAug 1, 2024
Photo by Markus Spiske on Unsplash

Terminology

class: A reference type that supports inheritance and dynamic dispatch, allowing for shared instances and polymorphic behaviour.

struct: A value type that supports static dispatch and provides efficient independent resources

dynamic dispatch: A method resolution process where the method to be used is determined at runtime. Enables polymorphism and method overriding.

static dispatch: A method resolution process where the method is determined as compile time. This leads to efficient and predictable performance.

Before We Start: class vs. struct

Memory

class instances are allocated on the heap

struct instances are allocated on the stack

Semantics

class instances use reference semantics. This means that multiple variables reference the same instance.

struct instances use value semantics. That means that stuct instances are copied when assigned to a new variable or passed to a function. This means that each instance is independent.

Inheritance

--

--

No responses yet