Sobes.tech
Middle+

When and under what conditions does dispatching start in Swift?

sobes.tech AI

Answer from AI

Method dispatch in Swift determines which code will be executed when a method of an object is called. The choice of dispatch type occurs at compile-time of Swift code.

There are three main types of dispatch in Swift:

  1. Direct Dispatch:

    • The fastest.
    • The function address is known at compile time.
    • Used by default for:
      • struct and enum (since they do not support class inheritance).
      • final class methods.
      • private class methods (internal and public do not support direct dispatch).
      • Global functions.
      • Static methods.
      • Extensions.
  2. Table Dispatch:

    • Used for class when polymorphism and inheritance are needed.
    • The address of the specific method implementation is determined at runtime using a virtual table (vtable).
    • Each class has its own vtable containing pointers to method implementations.
    • Supports inheritance and method overriding.
    class Animal { // Uses Table Dispatch
        func speak() {
            print("Unknown sound")
        }
    }
    
    class Dog: Animal { // Overrides, uses vtable
        override func speak() {
            print("Woof")
        }
    }
    
  3. Witness Table Dispatch:

    • Used for protocols.
    • Similar to table dispatch but uses a witness table to find the protocol method implementation for a specific type that conforms to the protocol.
    • Enables polymorphism with protocols.
    protocol Speakable { // Uses Witness Table Dispatch
        func speak()
    }
    
    struct Cat: Speakable { // Protocol implementation
        func speak() {
            print("Meow")
        }
    }
    

Conditions affecting the choice:

  • Data type: struct, enum, class, protocol.
  • Access modifiers: final, private, internal, public.
  • Inheritance: Ability to override methods.
  • Protocol conformance: Implementation of protocol methods.
  • Call context: Calling through a specific type or through a protocol/base class.

The Swift compiler tries to use direct dispatch where possible for performance optimization, but if polymorphism and inheritance support are needed, it switches to table or witness table dispatch. Explicitly marking methods as final or private allows forcing the use of direct dispatch.

When and under what conditions does dispatching start… - sobes.tech