The function printItem accepts any type T and prints it using string interpolation.
Step 2: Analyze calls with different types
First call passes an integer 42, second call passes a string "Hello". Both are valid and print accordingly.
Final Answer:
Item: 42
Item: Hello -> Option A
Quick Check:
Generic function prints each item correctly [OK]
Hint: Generic functions adapt to each type passed [OK]
Common Mistakes:
Expecting type mismatch error
Assuming output repeats same value
Confusing string interpolation syntax
4. Identify the error in this generic Swift function and fix it:
func addItems<T>(a: T, b: T) -> T {
return a + b
}
medium
A. No error, function works for all types.
B. Error: '+' operator not defined for all types T; constrain T to Numeric.
C. Error: Missing return type; should be '-> Int'.
D. Error: Parameters should be optional types.
Solution
Step 1: Analyze operator usage with generics
The '+' operator only works with types that support addition, not all types T.
Step 2: Apply type constraint to fix error
Constrain T to Numeric protocol to ensure '+' is valid for T.
Final Answer:
Error: '+' operator not defined for all types T; constrain T to Numeric. -> Option B
Quick Check:
Operator '+' requires Numeric constraint [OK]
Hint: Add constraints to generic types when using operators [OK]
Common Mistakes:
Assuming '+' works for any generic type
Ignoring need for protocol constraints
Changing return type unnecessarily
5. You want to create a generic function that returns the middle element of an array. Which approach ensures type safety and works for any array type in Swift?