What is the output of this Swift code?
protocol Describable { func describe() -> String } struct Person: Describable { var name: String func describe() -> String { return "Person named \(name)" } } func printDescription<T: Describable>(_ item: T) { print(item.describe()) } let p = Person(name: "Alice") printDescription(p)
Check how the describe() method is implemented and called.
The Person struct conforms to Describable and implements describe(). The generic function calls describe() on the passed instance, printing "Person named Alice".
Which statement about Swift type constraints with protocol conformance is true?
Think about what it means to constrain a generic type to a protocol.
When you constrain a generic type to a protocol, only types that conform to that protocol (implement all its requirements) can be used.
What error does this Swift code produce?
protocol Runnable { func run() } struct Car: Runnable { func run() { print("Car is running") } } func start<T: Runnable>(_ vehicle: T) { vehicle.run() } struct Bike {} start(Bike())
Check the type passed to the generic function and its protocol conformance.
The generic function requires a type conforming to Runnable. Bike does not conform, so the compiler errors.
Which option shows the correct syntax to constrain a generic type T to conform to protocol Equatable?
Recall the syntax for generic constraints in Swift function declarations.
The correct syntax is func name<T: Protocol>(...). Option A uses this correctly.
Given the following Swift code, how many items are in the filtered array after execution?
protocol Filterable { var isActive: Bool { get } } struct Item: Filterable { var isActive: Bool } func filterActive<T: Filterable>(_ items: [T]) -> [T] { items.filter { $0.isActive } } let items = [Item(isActive: true), Item(isActive: false), Item(isActive: true), Item(isActive: false)] let filtered = filterActive(items) print(filtered.count)
Count how many Item instances have isActive set to true.
Only two items have isActive == true, so the filtered array contains 2 elements.