Challenge - 5 Problems
Tuple Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift function returning a tuple?
Consider the following Swift function that returns a tuple. What will be printed when calling
result?Swift
func getCoordinates() -> (x: Int, y: Int) { return (x: 10, y: 20) } let result = getCoordinates() print("x: \(result.x), y: \(result.y)")
Attempts:
2 left
💡 Hint
Look at the tuple labels and values returned by the function.
✗ Incorrect
The function returns a tuple with x = 10 and y = 20. Accessing result.x and result.y prints those values exactly.
🧠 Conceptual
intermediate2:00remaining
What is the type of the tuple returned by this function?
Given this Swift function, what is the exact type of the returned tuple?
Swift
func getUserInfo() -> (name: String, age: Int) { return (name: "Alice", age: 30) }
Attempts:
2 left
💡 Hint
Check if the tuple has labels or not.
✗ Incorrect
The function returns a tuple with labels 'name' and 'age' of types String and Int respectively, so the type includes labels.
🔧 Debug
advanced2:00remaining
Why does this Swift function cause a compile error?
Examine the function below. Why does it cause a compile error?
Swift
func calculate() -> (Int, Int) { return (x: 5, y: 10) }
Attempts:
2 left
💡 Hint
Check if tuple labels in return match the declared return type.
✗ Incorrect
The function return type is an unlabeled tuple (Int, Int), but the return statement uses labeled tuple (x: 5, y: 10). This mismatch causes a compile error.
❓ Predict Output
advanced2:00remaining
What is the output of this function returning multiple values as a tuple?
What will be printed when running this Swift code?
Swift
func minMax(numbers: [Int]) -> (min: Int, max: Int)? { guard let first = numbers.first else { return nil } var currentMin = first var currentMax = first for number in numbers { if number < currentMin { currentMin = number } else if number > currentMax { currentMax = number } } return (min: currentMin, max: currentMax) } if let result = minMax(numbers: [3, 7, 2, 9, 4]) { print("Min is \(result.min), Max is \(result.max)") } else { print("Empty array") }
Attempts:
2 left
💡 Hint
The function finds the smallest and largest numbers in the array.
✗ Incorrect
The smallest number in the array is 2 and the largest is 9, so the output prints those values.
🧠 Conceptual
expert2:00remaining
How can you access tuple elements returned by a Swift function without using labels?
Given a Swift function that returns an unlabeled tuple, how do you access the elements?
Swift
func getValues() -> (Int, String) { return (42, "Answer") } let values = getValues()
Attempts:
2 left
💡 Hint
Unlabeled tuples use numeric indices starting at zero.
✗ Incorrect
Unlabeled tuple elements are accessed by .0, .1, etc. Using .first or subscripts is invalid for tuples.