Menu
Coddy logo textTech

Tuples

Part of the Fundamentals section of Coddy's Swift journey — lesson 68 of 86.

While arrays store multiple values of the same type, sometimes you need to group a few related values of different types together. This is where tuples come in handy.

A tuple is a fixed collection of values that can have different types. You create one by placing values inside parentheses, separated by commas:

let person = ("Alice", 25, true)
print(person)  // ("Alice", 25, true)

To access individual values, use their index with a dot:

let coordinates = (10.5, 20.3)
print(coordinates.0)  // 10.5
print(coordinates.1)  // 20.3

You can also name the elements for better readability:

let product = (name: "Laptop", price: 999.99)
print(product.name)   // Laptop
print(product.price)  // 999.99

Another useful feature is decomposing a tuple into separate variables:

let point = (3, 7)
let (x, y) = point
print(x)  // 3
print(y)  // 7

Tuples are perfect for returning multiple values from a function or grouping small amounts of related data without creating a full structure.

challenge icon

Challenge

Easy

You will receive three lines of input:

  1. A name (String)
  2. An age (Int)
  3. A score (Double)

Create a tuple called student with named elements: name, age, and score.

Then, decompose the tuple into three separate variables: studentName, studentAge, and studentScore.

Print the following three lines:

  1. The student's name accessed using the named element
  2. The student's age accessed using the index (dot notation with number)
  3. The decomposed score variable

Example: If the inputs are Emma, 21, and 95.5, your output should be:

Emma
21
95.5

Cheat sheet

A tuple is a fixed collection of values that can have different types. Create one using parentheses with comma-separated values:

let person = ("Alice", 25, true)

Access tuple elements by index using dot notation:

let coordinates = (10.5, 20.3)
print(coordinates.0)  // 10.5
print(coordinates.1)  // 20.3

Name tuple elements for better readability:

let product = (name: "Laptop", price: 999.99)
print(product.name)   // Laptop
print(product.price)  // 999.99

Decompose a tuple into separate variables:

let point = (3, 7)
let (x, y) = point
print(x)  // 3
print(y)  // 7

Try it yourself

// Read input
let name = readLine()!
let age = Int(readLine()!)!
let score = Double(readLine()!)!

// TODO: Write your code below
// 1. Create a tuple called 'student' with named elements: name, age, and score
// 2. Decompose the tuple into three separate variables: studentName, studentAge, and studentScore
// 3. Print the student's name using the named element (student.name)
// 4. Print the student's age using index notation (student.1)
// 5. Print the decomposed score variable (studentScore)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals