Challenge - 5 Problems
Swift Generic Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a generic swap function
What is the output of this Swift code that uses a generic function to swap two values?
Swift
func swapValues<T>(_ a: inout T, _ b: inout T) { let temp = a a = b b = temp } var x = 5 var y = 10 swapValues(&x, &y) print("x = \(x), y = \(y)")
Attempts:
2 left
💡 Hint
Think about what the swap function does to the values passed by reference.
✗ Incorrect
The generic function swaps the values of x and y by using inout parameters. After calling swapValues, x becomes 10 and y becomes 5.
❓ Predict Output
intermediate2:00remaining
Output of generic function with different types
What is the output of this Swift code using a generic function that prints the type and value?
Swift
func printValue<T>(_ value: T) { print("Value: \(value), Type: \(type(of: value))") } printValue(42) printValue("Hello")
Attempts:
2 left
💡 Hint
The generic function accepts any type and prints its value and type.
✗ Incorrect
The generic function printValue prints the value and its actual type. 42 is Int and "Hello" is String.
❓ Predict Output
advanced2:00remaining
Output of generic function with constraints
What is the output of this Swift code using a generic function constrained to Comparable?
Swift
func findMax<T: Comparable>(_ a: T, _ b: T) -> T { return a > b ? a : b } print(findMax(3, 7)) print(findMax("apple", "banana"))
Attempts:
2 left
💡 Hint
The function returns the greater of two Comparable values.
✗ Incorrect
The function findMax returns the larger value between a and b. 7 is greater than 3, and "banana" is lexicographically greater than "apple".
🔧 Debug
advanced2:00remaining
Identify the error in this generic function declaration
What error does this Swift code produce when compiling?
Swift
func printFirstElement<T>(array: [T]) -> T { return array[0] } print(printFirstElement(array: []))
Attempts:
2 left
💡 Hint
Consider what happens when accessing the first element of an empty array.
✗ Incorrect
The function tries to return the first element of an empty array, causing a runtime crash due to index out of range.
🧠 Conceptual
expert2:00remaining
Understanding generic function type inference
Given the generic function below, what is the inferred type of T when calling foo(5) and foo("test") respectively?
Swift
func foo<T>(_ value: T) -> String { return "Value is \(value)" } // Calls: // foo(5) // foo("test")
Attempts:
2 left
💡 Hint
Generic functions infer T based on the argument type at each call.
✗ Incorrect
The compiler infers T as Int when foo(5) is called and as String when foo("test") is called, allowing the function to work with different types.