0
0
Swiftprogramming~20 mins

Tuples for grouped values in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Tuple Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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).")
Aname is 30 years old and lives in city.
BAlice is 30 years old and lives in Paris.
C(name, age, city)
D30 is Alice years old and lives in Paris.
Attempts:
2 left
💡 Hint
Look at how the tuple is unpacked into variables and used in the print statement.
🧠 Conceptual
intermediate
2: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?
Alet person = (name: "Bob", age: "25")
Blet person = ("Bob", "25")
Clet person: (String, Int) = ("Bob", 25)
Dlet person: (name: String, age: Int) = ("Bob", "25")
Attempts:
2 left
💡 Hint
Check the types of each element in the tuple and their matching values.
🔧 Debug
advanced
2: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)
AThe tuple elements must be accessed only by name, not by unpacking.
BThe tuple elements are named, so you cannot unpack them into variables.
CYou cannot print multiple variables separated by commas in Swift.
DThe tuple 'coordinates' has only two elements, but three variables are used to unpack it.
Attempts:
2 left
💡 Hint
Count the number of elements in the tuple and the number of variables used to unpack.
📝 Syntax
advanced
2: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?
Alet info = ("John", 42, true)
Blet info = ("John"; 42; true)
Clet info = ["John", 42, true]
Dlet info = {"John", 42, true}
Attempts:
2 left
💡 Hint
Remember the syntax for tuples uses parentheses and commas.
🚀 Application
expert
2: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)
A(10, 5)
B(5, 10)
C(0, 0)
D(a, b)
Attempts:
2 left
💡 Hint
Look at how the tuple assignment swaps the values of 'a' and 'b'.