skip to content

A Swift method swizzled with `method_exchangeImplementations` changes for Objective-C callers but not for Swift callers; why, and what does `dynamic` change?

level: seniorimportance: should knowfreq 30%

answer

  1. two entry points for one method
  2. what @objc actually adds
  3. Swift callers skip the runtime
  4. every access through the runtime

basics

~20 s

For a class-body method, @objc only adds an Objective-C entry point; Swift callers still use the vtable or a direct call, so swizzling that entry misses them. @objc dynamic makes every access, Swift's included, a message the runtime can redirect.

solid answer

~50 s

Marking a method declared in the class body `@objc` registers an Objective-C **entry point** in the class's method list, a thunk that Objective-C code and selector-based calls reach through `objc_msgSend`. Swift callers do not use it: they call through the **vtable**, or directly and possibly inlined once the optimizer proves the target. `method_exchangeImplementations` swaps the entries in the Objective-C method list, so only message sends see the change. Adding `dynamic` makes **every** access go through the Objective-C runtime; the Swift book says such access is "never inlined or devirtualized by the compiler", so Swift callers see the swizzled implementation too. Key-value observing has the same requirement: the compiler warns when a property that is not `@objc dynamic` is passed to `observe(_:options:changeHandler:)`. The price is a message send on every call, so keep `dynamic` to members the runtime really must intercept. Since Swift 4 (SE-0160), members of an `NSObject` subclass are not `@objc` implicitly either.

code

swift · 22 lines
swift
import Foundation

class Tracker: NSObject {
  @objc func plainLog() -> String { "original" }
  @objc dynamic func dynamicLog() -> String { "original" }
  @objc func patched() -> String { "swizzled" }
}

func swap(_ a: Selector, _ b: Selector) {
  guard let m1 = class_getInstanceMethod(Tracker.self, a),
        let m2 = class_getInstanceMethod(Tracker.self, b)
  else { return }
  method_exchangeImplementations(m1, m2)
}

let t = Tracker()
swap(#selector(Tracker.plainLog), #selector(Tracker.patched))
print("plainLog from Swift:", t.plainLog())    // original
swap(#selector(Tracker.plainLog), #selector(Tracker.patched))  // undo

swap(#selector(Tracker.dynamicLog), #selector(Tracker.patched))
print("dynamicLog from Swift:", t.dynamicLog()) // swizzled

go deeper

for a junior

Recall that @objc exposes a method to Objective-C, and that dynamic makes even Swift calls go through the Objective-C runtime.

for a middle

Explain that @objc on a class-body method adds a second entry point while Swift callers keep the vtable or a direct call, and that dynamic is what routes Swift calls through objc_msgSend.

for a senior

Diagnose a swizzle or observer that fails only for Swift callers by reading the declaration, fix it with @objc dynamic, and keep dynamic off hot paths because it blocks inlining.

for a principal

Decide where Objective-C dynamism earns its cost in a mixed codebase, limiting swizzling and observing to declared, reviewed members rather than blanket @objc dynamic.

## One method, two entry points Swift classes on Apple platforms can participate in the **Objective-C runtime**, which finds methods at run time by **selector** through `objc_msgSend`. Marking a Swift method `@objc` exposes it to that runtime: the compiler emits an Objective-C-compatible **thunk** and lists it in the class's Objective-C method table, as the compiler's interop notes put it, "Swift methods marked or inferred as `@objc` are exposed as entries in the Objective-C method list for the class". That entry is for Objective-C callers. A Swift caller of a plain `@objc` method declared in the class body uses the normal Swift mechanism (an `@objc` method declared in an extension is the exception: it has no vtable slot, so Swift messages it): - a **vtable** call (`class_method` in SIL) when the method can be overridden; - a **direct call**, possibly inlined, when the optimizer proves the target, for example under whole-module optimization. ## Why the swizzle misses Swift callers **Method swizzling** with `method_exchangeImplementations(_:_:)` swaps the implementations stored in two entries of the Objective-C method list. Anything that reaches the method by message send sees the swap: Objective-C code, `perform(_:)`, target-action. Swift's vtable slot and any inlined copy are untouched, so Swift callers keep running the original body. The bug is easy to miss because the swizzle "works" when tested from Objective-C or through selectors. ## What `dynamic` changes The Swift book's definition of the `dynamic` modifier is precise: access to the member "is always dynamically dispatched using the Objective-C runtime" and "is never inlined or devirtualized by the compiler". With `@objc dynamic`, a Swift call compiles to `objc_method` in SIL, a message send, so it observes whatever implementation the method list holds. | Declaration | Swift callers use | Objective-C callers use | Swizzle visible to Swift? | |---|---|---|---| | `func` | vtable or direct | not callable | not swizzlable | | `@objc func` | vtable or direct | message send | no | | `@objc dynamic func` | message send | message send | yes | Two details trip people up: 1. **`NSObject` does not imply `@objc`.** Since Swift 4 (SE-0160), members of an `NSObject` subclass are no longer inferred `@objc`; overrides of `@objc` methods and implementations of `@objc` protocol requirements still are. 2. **`dynamic` without `@objc`** compiles with today's compiler, but it marks the member for Swift's own dynamic replacement, not the Objective-C runtime: Swift callers still use the vtable and the method has no selector to swizzle. The Swift book's older wording that `dynamic` members must be `@objc` reflects the Objective-C use. ## Key-value observing follows the same rule Foundation's automatic **key-value observing** intercepts property setters through the Objective-C runtime. A Swift assignment to an `@objc` property that is not `dynamic` calls the setter through Swift dispatch, so no notification fires. The Swift 6.4 compiler flags it: "passing reference to non-'@objc dynamic' property 'count' to KVO method 'observe(_:options:changeHandler:)' may lead to unexpected behavior or runtime trap". ## The cost and when to pay it - Every call to an `@objc dynamic` member is a message send, and the optimizer can neither inline it nor optimize across it. - In a hot path that cost is measurable; on a method called a few times per user action it is not. - Use `dynamic` only on members a runtime feature must intercept, such as key-value observing or a deliberate swizzle, and keep the rest of the class native Swift. ## Diagnosing it in practice When a swizzle or an observer works from Objective-C but not from Swift, work through the declaration and the build: 1. Check that the member is `@objc dynamic`, not `@objc` alone and not `dynamic` alone. 2. Check the compiler's warnings: the key-value observing warning above names the property it means. 3. Do not expect the build configuration to matter: Swift callers bypass the Objective-C entry at `-Onone`, through the vtable, and at `-O`, often through a direct or inlined call, alike. 4. Read the optimized SIL for the caller: a Swift call that reaches the runtime appears as `objc_method`; `class_method`, `function_ref` or an inlined body means the runtime is bypassed. The fix belongs on the declaration, not in the swizzling code, and it costs every caller a message send, so apply it to the members that need interception rather than to the whole class.

  • Does adding `dynamic` without `@objc` let Swift code see a swizzled Swift method?
    No. Today's compiler accepts plain `dynamic`, but it marks the member for Swift's own dynamic replacement mechanism rather than the Objective-C runtime. Swift callers still use the vtable, and without `@objc` the method has no selector in the Objective-C method list, so there is nothing for `method_exchangeImplementations` to swap.
  • Why does a key-value observer on a Swift property never fire when Swift code assigns the property?
    Automatic key-value observing works by intercepting the setter through the Objective-C runtime. A Swift assignment to a property that is not `@objc dynamic` calls the setter through Swift dispatch, which bypasses that interception. Declare the property `@objc dynamic`; the compiler warns when a non-`@objc dynamic` property is passed to `observe(_:options:changeHandler:)`.

  • Every method of an NSObject subclass is dispatched with objc_msgSend from Swift
  • @objc alone on a class-body method routes Swift callers through the runtime
  • A plain dynamic method without @objc can be swizzled from Swift
  • dynamic only changes how Objective-C sees the method, not Swift's calls
  • Making every method @objc dynamic has no runtime cost