SwiftQuiz
#10

Witness vs Extension Dispatch

  • protocols
  • dispatch
Swift 6.3.2 Report an issue

Verified quizzes have their expected answer checked by compiling and running the code with the listed Swift toolchain during the site build.

protocol P { func f() }
protocol Q {}

extension P {
    func f() {
        print("1")
    }
}

extension Q {
    func g() {
        print("1")
    }
}

struct S: P, Q {
    func f() {
        print("2")
    }

    func g() {
        print("2")
    }
}

let s = S()
let p: P = s
let q: Q = s

s.f()
p.f()
s.g()
q.g()
Hint

One of P and Q declares its method as a requirement. The other only adds the method in an extension. Why does that change which S implementation runs?

Your answer

What does this program do?