Protocol Defaults Through Class Inheritance
★★★- protocols
- dispatch
- inheritance
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 foo() -> String }
extension P {
func foo() -> String {
"P"
}
}
class A: P {
func foo() -> String {
"A"
}
}
class B: P {}
class C: B {
func foo() -> String {
"C"
}
}
print(A().foo())
print((A() as P).foo())
print(B().foo())
print((B() as P).foo())
print(C().foo())
print((C() as P).foo())
Hint
When a class conforms to a protocol but doesn't implement a requirement,
the compiler fills the witness slot with the protocol's default. That
choice is frozen at the point of the conformance declaration. What
does that mean for a subclass that later defines its own foo()?