Tuples let you keep several values together in one simple package. This helps when you want to return or pass multiple related values at once.
Tuples for grouped values in Swift
Introduction
Syntax
Swift
let tupleName = (value1, value2, value3) // Or with labels: let tupleName = (label1: value1, label2: value2, label3: value3)
You can access tuple values by position (e.g., tupleName.0) or by label (e.g., tupleName.label1) if labels are used.
Tuples are fixed in size and type once created.
Examples
Swift
let person = ("Alice", 30, true) print(person.0) // Prints "Alice" print(person.1) // Prints 30
Swift
let person = (name: "Bob", age: 25, isStudent: false) print(person.name) // Prints "Bob" print(person.age) // Prints 25
Swift
func getCoordinates() -> (x: Int, y: Int) { return (x: 10, y: 20) } let point = getCoordinates() print(point.x) // Prints 10 print(point.y) // Prints 20
Sample Program
This program defines a function that returns a tuple with user info. Then it prints each value using the tuple labels.
Swift
func getUserInfo() -> (name: String, age: Int, isMember: Bool) { return (name: "Emma", age: 28, isMember: true) } let user = getUserInfo() print("Name: \(user.name)") print("Age: \(user.age)") print("Member: \(user.isMember)")
Important Notes
Tuples are great for small groups of values but not for complex data. For bigger data, use structs or classes.
Tuple labels improve code readability and help avoid mistakes.
Summary
Tuples group multiple values into one simple package.
You can access tuple values by position or by label.
They are useful for returning multiple values from functions quickly.
Practice
1. What is a tuple in Swift used for?
easy
Solution
Step 1: Understand tuple purpose
Tuples combine multiple values into one grouped value without creating a new type.Step 2: Compare with other options
Classes, functions, and constants serve different purposes unrelated to grouping multiple values simply.Final Answer:
Grouping multiple values into a single compound value -> Option CQuick Check:
Tuple = grouped values [OK]
Hint: Tuples bundle values together simply [OK]
Common Mistakes:
- Confusing tuples with classes or structs
- Thinking tuples define functions
- Assuming tuples declare constants only
2. Which of the following is the correct syntax to declare a tuple with an Int and a String in Swift?
easy
Solution
Step 1: Check tuple declaration syntax
Correct tuple syntax uses parentheses with types inside, then assigns values in parentheses.Step 2: Validate each option
let person: (Int, String) = (25, "Alice") correctly declares a tuple type and assigns matching values. Others have syntax errors or wrong format.Final Answer:
let person: (Int, String) = (25, "Alice") -> Option AQuick Check:
Tuple syntax = (Type1, Type2) = (value1, value2) [OK]
Hint: Use parentheses for tuple types and values [OK]
Common Mistakes:
- Omitting parentheses around types
- Trying to declare types outside tuple parentheses
- Using incorrect colon placement
3. What will be the output of this Swift code?
let coordinates = (x: 10, y: 20) print(coordinates.x + coordinates.y)
medium
Solution
Step 1: Understand tuple with labels
The tuple has labels x and y with values 10 and 20 respectively.Step 2: Calculate the sum
Adding coordinates.x (10) and coordinates.y (20) results in 30.Final Answer:
30 -> Option DQuick Check:
10 + 20 = 30 [OK]
Hint: Access tuple values by labels with dot notation [OK]
Common Mistakes:
- Trying to print tuple without accessing elements
- Confusing tuple labels with dictionary keys
- Assuming tuple elements can't be accessed by label
4. Identify the error in this Swift code snippet:
let person = (name: "Bob", age: 30) print(person[0])
medium
Solution
Step 1: Check tuple access method
Tuples in Swift are accessed by position using dot and index (e.g., .0), not square brackets.Step 2: Analyze the code error
Using person[0] causes an error because square brackets are not valid for tuple indexing.Final Answer:
Tuples cannot be accessed by index using square brackets -> Option AQuick Check:
Use dot and number for tuple index, not brackets [OK]
Hint: Use dot and number for tuple index, not brackets [OK]
Common Mistakes:
- Using square brackets to access tuple elements
- Confusing tuples with arrays or dictionaries
- Assuming type annotations are mandatory for tuples
5. Given a function that returns a tuple with a person's name and age, how can you extract these values into separate variables?
func getPerson() -> (String, Int) {
return ("Emma", 28)
}
// Extract values herehard
Solution
Step 1: Understand tuple unpacking
Swift allows unpacking tuple return values directly into variables using parentheses.Step 2: Evaluate options
let (personName, personAge) = getPerson() correctly unpacks both values at once. let person = getPerson() let personName = person[0] let personAge = person[1] uses invalid indexing. let personName = getPerson().name let personAge = getPerson().age attempts to access nonexistent labels. let personName, personAge = getPerson() has invalid syntax.Final Answer:
let (personName, personAge) = getPerson() -> Option BQuick Check:
Tuple unpacking uses let (a, b) = tuple [OK]
Hint: Unpack tuples with let (a, b) = function() [OK]
Common Mistakes:
- Using square brackets to access tuple elements
- Attempting to access tuple elements by nonexistent labels
- Incorrect syntax for unpacking tuples
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
