What is the output of this Swift code using a generic function constrained to Comparable?
func findMax<T: Comparable>(_ a: T, _ b: T) -> T { return a > b ? a : b } let result = findMax(10, 20) print(result)
Think about which value is greater between 10 and 20.
The function findMax compares two values of a generic type T constrained to Comparable. It returns the greater value. Since 20 > 10, the output is 20.
What will be printed by this Swift code using a generic struct with two type parameters?
struct Pair<A, B> { var first: A var second: B } let pair = Pair(first: "Hello", second: 42) print(pair.first, pair.second)
Look at the order of the properties in the struct.
The struct Pair holds two values of generic types A and B. The instance pair has first as "Hello" and second as 42, so printing them outputs "Hello 42".
What error does this Swift code produce?
class Box<T> { var value: T init(value: T) { self.value = value } } let box = Box<Int>()
Check the initializer call and its parameters.
The class Box requires an argument value in its initializer. The code Box calls the initializer without arguments, causing a missing argument error.
Which of the following Swift generic type declarations is syntactically correct?
Remember the syntax for type constraints in generic declarations.
Option D correctly uses the syntax <T: Equatable> to constrain the generic type T. Options A, B, and D have syntax errors in the constraint declaration.
Given the following Swift code, what is the output?
protocol Container { associatedtype Item func add(_ item: Item) func count() -> Int } class Box<T>: Container { private var items = [T]() func add(_ item: T) { items.append(item) } func count() -> Int { items.count } } let box = Box<String>() box.add("Swift") box.add("Generics") print(box.count())
Consider how many items are added before counting.
The class Box conforms to Container protocol with Item as T. Two strings are added, so count() returns 2.