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 tuple unpacking?
Consider the following Swift code that uses a tuple to group values and then unpacks them. What will be printed?
Swift
let person = (name: "Alice", age: 30, city: "Paris") let (name, age, city) = person print("\(name) is \(age) years old and lives in \(city).")
Attempts:
2 left
💡 Hint
Look at how the tuple is unpacked into variables and used in the print statement.
✗ Incorrect
The tuple 'person' has named elements. Unpacking assigns each element to variables 'name', 'age', and 'city'. The print statement uses these variables to form the output string.
🧠 Conceptual
intermediate2:00remaining
Which tuple declaration is correct in Swift?
You want to create a tuple that groups a person's name as a String and age as an Int. Which of the following declarations is correct?
Attempts:
2 left
💡 Hint
Check the types of each element in the tuple and their matching values.
✗ Incorrect
Option C correctly declares a tuple with types (String, Int) and assigns matching values. Option C has age as a String instead of Int. Option C uses Strings for both elements without type annotation. Option C mismatches types by assigning a String to age which expects Int.
🔧 Debug
advanced2:00remaining
Why does this tuple code cause a compile error?
Examine the Swift code below. Why does it cause a compile-time error?
Swift
let coordinates = (x: 10, y: 20) let (a, b, c) = coordinates print(a, b, c)
Attempts:
2 left
💡 Hint
Count the number of elements in the tuple and the number of variables used to unpack.
✗ Incorrect
The tuple 'coordinates' has two elements (x and y). Trying to unpack into three variables (a, b, c) causes a compile error because the counts do not match.
📝 Syntax
advanced2:00remaining
Which option correctly creates a tuple with mixed types?
You want to create a tuple with a String, an Int, and a Bool in Swift. Which of the following is syntactically correct?
Attempts:
2 left
💡 Hint
Remember the syntax for tuples uses parentheses and commas.
✗ Incorrect
Option A uses parentheses and commas, which is the correct syntax for tuples. Option A uses semicolons which is invalid. Option A uses square brackets which create arrays, not tuples. Option A uses curly braces which is invalid syntax here.
🚀 Application
expert2:00remaining
What is the value of 'result' after this tuple swap?
Given the following Swift code that swaps two values using tuples, what is the value of 'result' after execution?
Swift
var a = 5 var b = 10 (a, b) = (b, a) let result = (a, b)
Attempts:
2 left
💡 Hint
Look at how the tuple assignment swaps the values of 'a' and 'b'.
✗ Incorrect
The tuple assignment swaps the values of 'a' and 'b'. Initially a=5 and b=10, after swap a=10 and b=5. So 'result' is (10, 5).