Back to questions
JuniorTheoryCommon
What does the program print?
protocol Greeter {
func greet() -> String
}
extension Greeter {
func greet() -> String { "Hi" }
}
struct Robot: Greeter {}
struct Cat: Greeter {
func greet() -> String { "Meow" }
}
print(Robot().greet(), Cat().greet())Hi Meow
- Expecting
Hi Hi: thinking the protocol extension's method wins. A type's own method replaces the default, soCatanswersMeow. - Expecting a compile error because
Robothas nogreet()of its own. The default implementation in the protocol extension meets the requirement.
- What would the program print if
greet()were removed from the protocol but kept in the extension and inCat, and called through[any Greeter]? - How could
Catreuse the default greeting inside its owngreet()?