
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Variables
- Swift - Constants
- Swift - Literals
- Swift - Comments
- Swift Operators
- Swift - Operators
- Swift - Arithmetic Operators
- Swift - Comparison Operators
- Swift - Logical Operators
- Swift - Assignment Operators
- Swift - Bitwise Operators
- Swift - Misc Operators
- Swift Advanced Operators
- Swift - Operator Overloading
- Swift - Arithmetic Overflow Operators
- Swift - Identity Operators
- Swift - Range Operators
- Swift Data Types
- Swift - Data Types
- Swift - Integers
- Swift - Floating-Point Numbers
- Swift - Double
- Swift - Boolean
- Swift - Strings
- Swift - Characters
- Swift - Type Aliases
- Swift - Optionals
- Swift - Tuples
- Swift - Assertions and Precondition
- Swift Control Flow
- Swift - Decision Making
- Swift - if statement
- Swift - if...else if...else Statement
- Swift - if-else Statement
- Swift - nested if statements
- Swift - switch statement
- Swift - Loops
- Swift - for in loop
- Swift - While loop
- Swift - repeat...while loop
- Swift - continue statement
- Swift - break statement
- Swift - fall through statement
- Swift Collections
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift Functions
- Swift - Functions
- Swift - Nested Functions
- Swift - Function Overloading
- Swift - Recursion
- Swift - Higher-Order Functions
- Swift Closures
- Swift - Closures
- Swift-Escaping and Non-escaping closure
- Swift - Auto Closures
- Swift OOps
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift-Overriding
- Swift - Initialization
- Swift - Deinitialization
- Swift Advanced
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Error handling
- Swift - Concurrency
- Swift - Type Casting
- Swift - Nested Types
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift - Function vs Method
- Swift - SwiftyJSON
- Swift - Singleton class
- Swift Random Numbers
- Swift Opaque and Boxed Type
Swift - Tuples
Swift Tuples store multiple values in a single compound value and can hold different or same data types.
Swift Tuples
Tuples are used to store a group of values in a single value, for example (32, "Swift Programming") is a tuple with two values that are 23 and "Swift Programming". Tuples can store multiple values and each value is separated by a comma. It can store values of the same or different data types. They are helpful when we want to return multiple values together.
Tuples are commonly used by the functions to return multiple values at the same time. Tuples are not used for complex data structures; they are useful for simple groups of related data.
Create a Tuple
We can create a tuple using parentheses () and store its elements by providing comma-separated values.
Following is the syntax to create a tuple:
var myValue = (value1, value2, value3, value4, , valueN)
For example:
var student = ("Robin", 21)
Here, student
is a tuple with a string value "Robin" and an integer value 21.
Access Tuple Elements
Similar to an array, each tuple element is represented by an index where the first element is at index 0 and the last element is N-1 (where N is the total number of elements in a tuple). We can access the elements of the tuple with the help of dot notation followed by the elements index:
var result = tupleName.indexValue
Swift Tupe Example
In this example, we are creating a tuple, accessing and printing its elements:
import Foundation // Creating a tuple var Emp = ("Romin", 321, "Delhi") // Accessing the elements of Tuple var name = Emp.0 var id = Emp.1 var city = Emp.2 // Displaying the result print("Employee name =", name) print("Employee id =", id) print("Employee city =", city)
The output of the above example is:
Employee name = Romin Employee id = 321 Employee city = Delhi
Modifying Tuple Element
We can modify (change) the value of a specific tuple element by assigning a new value to it.
Example
This example demonstrates modifying tuple elements:
// Create tuple with employee details var employee = ("Rahul Sharma", 35000.0) print("Original Tuple: ") // Access tuple elements print("Name:", employee.0) print("Salary:", employee.1) // Modify salary employee.1 = 40000.0 print("\nTuple After Modification: ") // Access tuple elements print("Name:", employee.0) print("Salary:", employee.1)
The output of the above example is:
Original Tuple: Name: Rahul Sharma Salary: 35000.0 Tuple After Modification: Name: Rahul Sharma Salary: 40000.0
Tuple With Different Data types
In a tuple, we are allowed to store data of different types like (Int, Int, Float), (Float, Double, String), etc. You can also store data of the same data type like (Int, Int, Int), etc.
Example
Swift program to create a tuple of different data types.
import Foundation // Creating a tuple with data of different data types var myTuple = ("Mona", 21, "Mumbai", 101) // Accessing the elements of Tuple var name = myTuple.0 var age = myTuple.1 var city = myTuple.2 var id = myTuple.3 // Displaying the result print("Student name =", name) print("Student age =", age) print("Student city =", city) print("Student id =", id)
The output of the above example is:
Student name = Mona Student age = 21 Student city = Mumbai Student id = 101
Assigning Tuple to Separate Variables
We can assign the value of a tuple to a separate constant or variable so that we can access them using the name of that constant or the variable. Here the count of the constant or variable should be equal to the tuples values.
Syntax
Following is the syntax of assigning tuple values to a separate constant or variable −
let (name1, name2) = tuple
Example
Swift program to create a tuple whose values are assigned to a set of constants.
import Foundation // Creating a tuple var myTuple = ("Mickey", 21, "Pune") // Assigning tuple to a set of constants let(name, age, city) = myTuple // Accessing the value of tuples according to the constant print("Student name =", name) print("Student age =", age) print("Student city =", city)
The output of the above example is:
Student name = Mickey Student age = 21 Student city = Pune
Tuple with Underscore
We are allowed to use an underscore "_" with a tuple. It will ignore the part of the tuple with an underscore while decomposing the tuple. Or in other words, we can say that by using underscore we can ignore some tuples values. We are allowed to use multiple underscores with the same tuple to ignore multiple values.
Syntax
Following is the syntax of a tuple with an underscore −
let (name1, name2, _) = tuple
Example
Swift program to create a tuple with underscore "_".
import Foundation // Creating a tuple var myTuple = (21, "Pune", "CSE") // Assigning a tuple to a set of constants let(age, _, branch) = myTuple // Accessing the values of tuples print("Student age =", age) print("branch =", branch)
The output of the above example is:
Student age = 21 branch = CSE
Assigning Names to Individual Values in a Tuple
In Swift, we are allowed to assign names to the individual elements of the tuple. We can also access the tuples elements according to their names.
Syntax
Following is the syntax for assigning names to a tuples elements −
let myTuple = (id: 102, name: "Sona")
Example
Swift program to create and access tuple elements according to their names.
import Foundation // Creating a tuple var myTuple = (name: "Mona", branch: "ECE", year: 2022) // Accessing the values of tuples according to their names print("Student name =", myTuple.name) print("Branch =", myTuple.branch) print("Current Year", myTuple.year)
The output of the above example is:
Student name = Mona Branch = ECE Current Year 2022
Named Tuples
In Swift, we can also create a named tuple where we can provide the names for each element of the tuple.
Example
This example demonstrates modifying elements of a named tuple:
// Create named tuple var employee = (name: "Rahul Sharma", salary: 35000.0) print("Original Tuple: ") // Access tuple elements print("Name:", employee.name) print("Salary:", employee.salary) // Modify salary employee.salary = 40000.0 print("\nTuple After Modification: ") // Access tuple elements print("Name:", employee.name) print("Salary:", employee.salary)
The output of the above example is:
Original Tuple: Name: Rahul Sharma Salary: 35000.0 Tuple After Modification: Name: Rahul Sharma Salary: 40000.0
Nested Tuple
Swift allows creating nested tuple where a tuple can be used as an element of another tuple.
Example
This example demonstrates a nested tuple:
// Create nested tuple with employee details var employee = (personal: (name: "Rahul Sharma", age: 30), job: (designation: "Developer", salary: 35000.0)) print("Original Tuple: ") // Access nested tuple elements print("Name:", employee.personal.name) print("Age:", employee.personal.age) print("Designation:", employee.job.designation) print("Salary:", employee.job.salary) // Modify salary employee.job.salary = 40000.0 print("\nTuple After Modification: ") // Access nested tuple elements print("Name:", employee.personal.name) print("Age:", employee.personal.age) print("Designation:", employee.job.designation) print("Salary:", employee.job.salary)
The output of the above example is:
Original Tuple: Name: Rahul Sharma Age: 30 Designation: Developer Salary: 35000.0 Tuple After Modification: Name: Rahul Sharma Age: 30 Designation: Developer Salary: 40000.0
Adding/Removing Elements From Tuple
Swift does not allow to add or remove elements from a tuple. Tuples cannot change their size. We can replace their existing values only.
Example
This example demonstrates that Swift does not allow adding or removing elements from a tuple after it is created:
// Create a tuple with two elements var employee = (name: "Rahul Sharma", salary: 35000.0) print("Name:", employee.name) print("Salary:", employee.salary) // Attempting to add and remove elements employee.age = 30
The output of the above example is:
Warnings/Errors: main.swift:9:10: error: value of tuple type '(name: String, salary: Double)' has no member 'age' 7 | 8 | // Attempting to add and remove elements 9 | employee.age = 30 | `- error: value of tuple type '(name: String, salary: Double)' has no member 'age