skip to content

In Swift, which dispatch mechanism handles a call to a struct method, an overridable class method, a protocol requirement and an `@objc dynamic` method?

level: middleimportance: must knowfreq 65%

answer

  1. chosen per call site
  2. what is known about the receiver
  3. a slot per class, a table per conformance
  4. the Objective-C runtime only on request

basics

~20 s

Swift picks per call site: struct, enum and final methods are direct calls; overridable class methods use the class vtable; protocol requirements called on a generic or existential value use a witness table; @objc dynamic members use objc_msgSend.

solid answer

~50 s

The compiler chooses from what it knows at the call site. A method of a **struct** or **enum**, a `final` or `static` member, or a protocol requirement called on a value whose concrete type is known, compiles to a **direct call**. A non-final class method or property is looked up in the class's **vtable**, a table of function pointers at fixed slots that subclasses fill with their overrides. A protocol requirement called through a generic parameter `T: Drawable` or an `any Drawable` value goes through a **witness table**, one per conformance, passed to the generic function as a hidden argument or stored inside the existential container. A member marked `@objc dynamic` is sent as an Objective-C message with `objc_msgSend`. With optimization on, the compiler turns vtable and witness-table calls into direct calls whenever it can prove the target; a `dynamic` member is never devirtualized.

code

swift · 23 lines
swift
import Foundation

protocol Drawable { func draw() -> String }

struct Badge: Drawable { func draw() -> String { "badge" } }

class Sprite { func draw() -> String { "sprite" } }

class LegacyView: NSObject {
  @objc dynamic func draw() -> String { "legacy" }
}

func paint<T: Drawable>(_ item: T) -> String { item.draw() }

let badge = Badge()
let sprite: Sprite = Sprite()
let anyItem: any Drawable = badge

print(badge.draw())          // static: the concrete struct type is known
print(sprite.draw())         // vtable: Sprite.draw can be overridden
print(paint(badge))          // witness table passed to the generic function
print(anyItem.draw())        // witness table stored in the existential
print(LegacyView().draw())   // objc_msgSend: @objc dynamic

go deeper

for a junior

Recall that struct and final methods are direct calls, class methods use a vtable, and protocol calls through generics or any use a witness table.

for a middle

Explain the four mechanisms, what the compiler must know to pick each, where the witness table lives for a generic versus an existential, and why only dynamic forces Objective-C messaging.

for a senior

Read optimized SIL for class_method, witness_method and objc_method to see which calls survived, and choose struct, final class, generic or existential storage with that cost in mind.

for a principal

Use the mechanisms to set review guidance: which abstractions a hot path may use, where final is expected, and where Objective-C dynamism is justified by a runtime feature rather than habit.

## Dispatch is chosen per call site **Dispatch** is how a running program finds the code for a call. Swift does not use one mechanism for every call: it has four, and the compiler picks one for each call from what it knows about the **receiver** (the value before the dot) at that point in the source. The same method can be called directly in one place and indirectly in another. ## The four mechanisms | Mechanism | Used for | How the target is found | Can `-O` make it direct? | |---|---|---|---| | **Direct (static)** | struct and enum methods, `final` and `static` class members, native members declared in a class extension, requirements called on a known concrete type | the compiler names the function | already direct | | **vtable** | non-final class methods, properties and subscripts | fixed slot in the class's table of function pointers | yes, when no override is possible or the exact class is known | | **Witness table** | protocol requirements called through a generic parameter or an existential | per-conformance table of the requirement implementations | yes, when the concrete type is known, for example after specialization | | **Objective-C message** | members marked `@objc dynamic`, and `@objc` members declared in a class extension | `objc_msgSend` looks the selector up in the class's method list | no, by definition | ## Witness tables in more detail A **witness table** records, for one type's conformance to one protocol, which function implements each requirement. `Badge: Drawable` has one; `Sprite: Drawable` would have another. - In an unspecialized generic function `func paint<T: Drawable>(_ item: T)`, the caller passes the type's metadata and its `Drawable` witness table as hidden arguments; `item.draw()` calls through that table. - An `any Drawable` value is an **existential container**: an inline buffer for the value, a pointer to its type metadata, and one witness-table pointer per protocol. A call opens the container and calls through that stored table. - For a protocol constrained to `AnyObject`, the container holds only the object reference plus the witness tables, but the call still uses the witness table. - Only **requirements** have witness-table entries. A method that exists only in a protocol extension is not dispatched this way; that trap is covered with protocol default implementations. Calling a requirement on a value whose concrete type is known, such as `badge.draw()` where `badge` is a `Badge`, needs no table at all: the compiler calls `Badge.draw` directly. ## Objective-C messaging On Apple platforms Swift can expose members to the Objective-C runtime. The Swift book states that access to a `dynamic` member "is always dynamically dispatched using the Objective-C runtime" and "is never inlined or devirtualized by the compiler". `@objc` on its own only adds an Objective-C entry point: Swift callers of an `@objc` method declared in the class body still use the vtable. (An `@objc` member declared in a class extension has no vtable slot, so Swift messages it too.) Messaging is what makes method swizzling and key-value observing work. Its cost is less the lookup itself than what it rules out: the compiler can assume nothing about the target, so it never inlines it. ## The same method, four ways Take a protocol `Drawable` with a `draw()` requirement, a struct `Badge` that conforms to it, a class `Sprite` and an `NSObject` subclass `LegacyView` whose `draw()` is `@objc dynamic`. `badge.draw()` names a struct method directly. `sprite.draw()` goes through `Sprite`'s vtable, because a subclass of `Sprite` could override it. `paint(badge)` enters a generic function that receives `Badge`'s `Drawable` witness table and calls through it, and `anyItem.draw()` finds the same table inside the existential container. `LegacyView().draw()` sends the `draw` message through `objc_msgSend`. Under `-O`, the compiler can see the concrete types in the first four calls and may make them all direct; the fifth stays a message send because `dynamic` forbids anything else. ## How to check which mechanism you got The compiler's intermediate language names each mechanism with its own instruction: 1. `function_ref` followed by `apply`: a direct call. 2. `class_method`: a vtable lookup. 3. `witness_method`: a witness-table lookup. 4. `objc_method`: an Objective-C message send. Run `xcrun swiftc -O -emit-sil File.swift` to see what survives optimization, or `-emit-silgen` to see the unoptimized choice. ## Common confusions - Classes are not always dynamic: `final`, `private` and whole-module optimization let the compiler call many class methods directly. - Protocols are not always dynamic: a requirement called on a concrete type, or inside a specialized generic, is direct. - Structs have no vtable; nothing about a struct method is looked up by name at run time. - `@objc` is not the same as `@objc dynamic`; for a method declared in the class body, only `dynamic` forces messaging for Swift callers.

  • Does a call to a Swift protocol requirement always go through a witness table?
    No. The witness table is needed only when the concrete type is unknown at the call site: inside an unspecialized generic function or through an `any` existential. Calling the requirement on a value of a known type, such as a `Badge`, compiles to a direct call, and once the optimizer specializes a generic function for a concrete type its calls become direct as well.
  • What changes for dispatch when a Swift protocol is constrained to `AnyObject`?
    Only classes can conform, so an `any P` value is a class existential: the object reference plus one witness-table pointer per protocol, with no inline value buffer or separate metadata pointer. Requirement calls still go through the witness table, but the compiler knows the value is a reference, which Swift's optimization guide notes lets ARC handle it more cheaply.

  • Every protocol method call in Swift goes through a witness table
  • Struct methods are dispatched through a vtable, just more cheaply
  • Marking a method in the class body @objc makes Swift callers use objc_msgSend
  • Witness tables are looked up by method name at run time
  • All class methods are dynamic in Swift, so classes are always slower