What is the output of this Swift code using generics?
func echo<T>(_ value: T) -> T { return value } let result = echo("Hello") print(result)
Think about how generics keep the type consistent.
The generic function echo returns the same type it receives. Since it receives a String, it returns a String. So the output is Hello.
Why do generics in Swift help prevent type errors?
Think about when type errors are caught.
Generics enforce consistent use of the same type throughout the code, so if you try to mix types, the compiler will catch it before running the program.
What error will this Swift code produce?
func add<T>(_ a: T, _ b: T) -> T { return a + b } let result = add(5, 10)
Consider what operators are available for generic types.
The generic type T does not guarantee that '+' operator is defined. The compiler cannot apply '+' to generic types without constraints, so it raises a compile-time error.
What is the output of this Swift code using a generic struct?
struct Box<T> { var value: T } let intBox = Box(value: 42) print(intBox.value)
Think about how generics store values.
The generic struct Box stores a value of type T. Here it stores an Int 42, so printing intBox.value outputs 42.
Choose the best explanation for how generics improve both safety and reusability in Swift code.
Think about compile-time checks and code reuse.
Generics let you write one piece of code that works with many types safely by checking types at compile time. This reduces bugs and avoids writing similar code multiple times.