Table of contents
1.
Introduction
2.
Tuples
2.1.
Unnamed Tuples
2.2.
Named Tuples
3.
Nested Tuples
3.1.
Example:
3.2.
Output:
4.
Access Tuples value
4.1.
Like an Array
4.2.
Using Name or Labels
5.
Use cases of Tuples
5.1.
For returning multiple values
5.1.1.
Code
5.1.2.
Output
5.2.
Tuples with Switch Case Statement
5.2.1.
Code
5.2.2.
Output
5.3.
Using switch statement with enum
5.3.1.
Code
5.3.2.
Output
6.
Frequently Asked Questions
6.1.
Which Version of Swift introduced Tuples?
6.2.
Is it possible to loop over a tuple in Swift?
6.3.
In Swift, are tuples immutable?
6.4.
Are Swift tuples ordered?
7.
Conclusion
Last Updated: Mar 27, 2024

Swift Tuples

Introduction

Swift is a replacement for Objective C, which incorporates contemporary programming theory concepts and a streamlined syntax. It was first released in 2014 with a few revisions over the years. During its initial launch, it was defined as "Objective-C without the baggage of C."

This article will discuss the Swift tuples and their use cases with examples.

Tuples

Tuple types are unfamiliar concepts for Objective-C programmers, and they can be mistaken for either a struct or a class. They're, however, far more fundamental than both of them. We can think of them as a small struct.

According to Apple's Swift Types documentation: A tuple type is a collection of zero or more types separated by commas and contained in parenthesis.

Tuples are used to combine several values into a single compound value. The values we declare in a tuple can be of any type, and there is no requirement that they are of the same kind.

There are two sorts of tuples accessible in Swift: unnamed tuples and named tuples.

Unnamed Tuples

Unnamed tuples are used in Swift to bundle many values into a single value by using parenthesis, which must be separated by commas.

Here's a simple example of defining unnamed tuples in a swift programming language.

let course = ( “swift” , 10)
Or
var course: (String, Int) = (“swift” , 10)

If you look at the unnamed tuple values above, you'll notice that we've combined string and integer values into a single compound value. We can use immutable let or mutable var depending on our needs.

Named Tuples

Named tuples are used in Swift to combine many values into a single by using parenthesis. These values must be defined with named variables and separated by commas.

Here's a simple example of defining named tuples in a swift programming language.

let course = ( name:“swift” , id:10)
 Or
var course: (name: String,id:  Int) = (“swift” , 10)

We can use any kind of value within the tuple, but we can't use the same type as arrays.

Nested Tuples

A tuple can be created as an element of another tuple in Swift. For example,

var names = ("X",  "Y",  "Z", ( "x",  "y",  "z") )

As the third element of the names tuple, we have a tuple ("x", "y", "z"). This is referred to as a nested tuple.

Example:

var names = ("X", "Y", "Z", ("x", "y", "z"))

// access first element
print(names.0)   // prints "X"

// access the third element
print(names.3)

// access nested tuple
print(names.3.0)  // prints "x"

Output:

Access Tuples value

There are two ways to access tuple values:

  1. Array-like access using the index number.
  2. Use the names or values label to access.

With examples, we'll learn how to access these tuples values in Swift.

Like an Array

Each tuple element is represented by index numbers (0, 1,...), similar to an array, with the first element at index 0.

To access tuple elements, we use the index number. For example,

// accessing the first element
course.0
// accessing second element
course.1

Using Name or Labels

We can also access the tuples using the given name or value labels. For example,

//accessing the course name
course.name
//accessing the course id
course.id

When we don’t specify our tuple’s name or label(unnamed tuples). for example,

let book = ( 30 , 10)

In this scenario, we can use index numbers to get access:

book.0  //30
book.1  //10

Use cases of Tuples

In a swift programming language, we may utilise tuples to group many values into a single compound value that we can use in applications based on our needs. Some of the use-cases of Tuples are as follows:

For returning multiple values

The most common use case for tuples is to return several values from a function. Here's an example:

Code

func getcourse() -> (name: String, week: Int){
   let thecourse = "Swift"
   let theweek = 8
   return(thecourse, theweek)
}
print(getcourse())

Output

Tuples with Switch Case Statement

The switch statement in Swift allows us to compare a given value to many possible matching options and take the appropriate action.

Here is a simple example of using a tuple with a switch case expression in Swift programming language,

Code

let coordinates: (x: Int, y: Int, z: Int) = (1, 5, 0)
switch coordinates {
case (0, 0, 0):
print("Origin")
case (_, 2, 5):
print("On the x axis.")
case (1, _, 0):
print("On the y axis.")
case (1, 2, _):
print("On the z axis.")
default:
print("Somewhere in the space")
}

Output

Using switch statement with enum

In Swift, enumerations let us create a common type for a group of finite and related values.

Let's start with defining our first enum named Seasons:

enum seasons {
    case spring
    case summer
    case rainy
    case winter
}

Because the collection of declared values in an enum is finite, switching on the enum values rather than utilising numerous if-else statements is highly popular.

Here's an example of a switch statement in Swift that matches Operator enum values:

Code

enum seasons {
   case spring
   case summer
   case rainy
   case winter
}

let currentseason: seasons = .summer
switch currentseason {
        case .spring:
               print("Blossom by blossom the spring begins.")
        case .summer:
               print("It's so hot! Time for an Icecream.")
        case .rainy:
               print("It's raining. Bring an umbrella!")
        case .winter:
           print("It's cool out, wear a jacket!")
}

Output

Frequently Asked Questions

Which Version of Swift introduced Tuples?

Tuples are a new type in Swift 4 used to group many values into a single compound value. A tuple's values can be of any kind, and they don't have to be of the same type.

 

Is it possible to loop over a tuple in Swift?

Iterating over tuples is not presently supported in Swift. We can perform common sequence operations like indexing, slicing, concatenation, multiplication, and finding the minimum and maximum value on tuples.

 

In Swift, are tuples immutable?

Tuples are compound data types; declaring them as let makes them and their "members" immutable, whereas defining them as var makes them mutable.

 

Are Swift tuples ordered?

A tuple is a list of values sorted and separated by commas and enclosed in parentheses.

Conclusion

This article extensively discussed Swift Tuples, their types, how to access them, and their use cases, such as using tuples for returning multiple values and using tuples with switch case statements and examples. Check out the definitive swift tutorial for beginners to know more about Swift.

We hope this blog has helped you enhance your knowledge regarding tuples in Swift. You can learn more about IOS by visiting the Ios and os related articles in CodingNInjas Blogs.  

Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations, and much more!!

We wish you Good Luck! Keep coding and keep reading Ninja!!

Live masterclass