Predict method dispatch through a protocol type

Practice identifying when Swift uses dynamic dispatch for protocol requirements and when protocol extension methods are resolved statically.

SwiftProtocols

Practice

A Car conforms to Vehicle and overrides start(), but the protocol extension also defines start(). This shows up in real protocol-oriented APIs: a method that looks like an override may not run when the value is used through a protocol-typed reference.

Run the code and note which start() executes. Interviewers usually follow with four questions — work through each one in your head (or out loud) after you see the output:

  1. What's the output?
  2. Why does Swift choose that implementation?
  3. What changes if start() exists only in the protocol extension (not in the protocol)?
  4. Explain the difference between static dispatch and dynamic dispatch in this example.
swift 5.2

Run to compile this snippet and inspect its output. Runs Swift 5.2 on the server (Linux); UIKit, SwiftUI, and long-running async are not supported.