Understanding Swift - Tuples
What Are Tuples in Swift?
A tuple in Swift allows you to store multiple values in a single variable. Unlike arrays, tuples can hold different data types, making them useful for grouping related values without defining a custom structure.
For example, this is a tuple:
let user = (32, "Swift Programming")
Here, the tuple contains an integer (32) and a string ("Swift Programming").
Why Use Tuples?
- Store multiple values in a single variable
- Group related data without creating a custom struct
- Return multiple values from functions efficiently
- Maintain type safety with mixed data types
How to Create and Access Tuples in Swift
Declaring a Tuple in SwiftThe general syntax for tuples:
var myTuple = (value1, value2, value3, …, valueN)
You can access tuple elements using dot notation (.index):
var result = tupleName.indexValue
Tuples can store values of different data types, such as Int, String, Float, or Bool.
Example: Creating and Accessing a Tuple
import
Foundation
// Creating a tuple
var employee
= ("Romin",
321, "Delhi")
// Accessing elements using index positions
var name
=
employee.0
var id
=
employee.1
var city
=
employee.2
// Displaying results
print("Employee Name =", name)
print("Employee ID =", id)
print("Employee City =", city)
Output
Employee ID = 321
Employee City = Delhi
Assigning Tuple Values to Separate Variables
Instead of accessing elements with dot notation, you can assign tuple values to variables directly.
Example: Assigning Tuple Values to Constants
import
Foundation
// Creating a tuple
var student
= (
"Mickey" , 21 ,
"Pune" )
// Assigning tuple values to variables
let (name, age, city) = student
// Printing the values
print(
"Student Name =", name )
print(
"Student Age =", age )
print(
"Student City =", city )
Output
Student Age = 21
Student City = Pune
Ignoring Tuple Elements Using Underscore (_)
If you only need specific values from a tuple, use underscore (_) to ignore the rest.
Example: Skipping Tuple Values
import
Foundation
// Creating a tuple
var student
= (
"Mickey" , 21 ,
"Pune" )
// Ignoring the second value
let (name, _, city) = student
// Printing the values
print(
"Student name =", name )
print(
"Student City =", city )
Output
Student City = Pune
Named Tuples in Swift
You can assign custom names to tuple elements instead of using index numbers.
Example: Creating Named Tuples
import
Foundation
// Creating a tuple
var student
= (name:
"Mickey" ,age:
21 , city
: "Pune" )
// Printing the values
print(
"Student name =", student.name )
print(
"Student Age =", student.age )
print(
"Student City =", student.city )
Output
Student Age = 21
Student City = Pune