What is the output of this Swift code using protocol extensions?
protocol Greetable { func greet() -> String } extension Greetable { func greet() -> String { return "Hello from protocol extension" } } struct Person: Greetable { func greet() -> String { return "Hello from Person" } } let p: Greetable = Person() print(p.greet())
Remember that when a concrete type implements a protocol method, that implementation is called instead of the protocol extension's default.
The variable p is typed as Greetable, but the instance is Person. Since Person provides its own greet() method, that method is called, not the protocol extension's default.
Which of the following is a key advantage of using protocols over base classes in Swift?
Think about how Swift handles multiple inheritance and code reuse.
Swift classes support single inheritance only, but types can conform to multiple protocols, allowing multiple behavior inheritance.
Given this code, why does the protocol extension method describe() not get called when using a concrete type?
protocol Describable { func describe() -> String } extension Describable { func describe() -> String { return "Default description" } } struct Item: Describable { // No describe() implementation here } let item = Item() print(item.describe())
Protocol extensions can provide default implementations that conforming types inherit automatically.
Since Item does not implement describe(), the protocol extension's default is used, so "Default description" is printed.
Which option contains a syntax error when trying to conform to a protocol with an associated type?
protocol Container { associatedtype Item func append(_ item: Item) } struct IntStack: Container { var items = [Int]() func append(_ item: Int) { items.append(item) } }
Consider whether the method modifies the struct's properties and what keyword is needed.
Since append modifies the items array, the method must be marked mutating in a struct. Option D misses this, causing a compiler error.
Which statement best explains how protocol-oriented programming improves flexibility in Swift code?
Think about how protocols and extensions enable code reuse without inheritance.
Protocol-oriented programming encourages sharing behavior via protocols and extensions, allowing types to compose behavior flexibly without rigid class inheritance.