What is Tuple?

Tuple is a data type in swift which can hold multiple values.

Creating a Tuple

simple way

let person = ("sandesh", "sardar", 27)

using named parameter

let person = (firstName:"sandesh", lastName:"sardar", age:27)

creating empty tuple

let person : (String, String, Int) 
OR
let person : (firstName:String, lastName:String, age:Int) = nil

Reading from a Tuple

to read and store all tuple value in different variable

let (personFirstName, personLastName, personAge) = person
personFirstName //output: "sandesh"
personLastName //output: "sardar"
personAge //output: 27

to read only particular values use “_” to ignore

let (personFirstName, personLastName, _) = person

read specific tuple value and store to variable

let firstname = person.0   //output: "sandesh" 
let lastname = person.1   //output: "sardar" 
let age = person.2   //output: 27

if tuple is with named parameter

let firstname = person.firstName   //output: "sandesh" 
let lastname = person.lastName   //output: "sardar" 
let age = person.age  //output: 27

Returning a Tuple from a Function

func personDetails() -> (firstName:String, lastName:String, age:Int){
let firstname = "sandesh"
let lastname = "sardar"
let age = 27
return (firstname, lastname, age)
}

Access Control and Tuples

A tuple’s access level is determined by its constituents, and is not set directly like you would for a property or function.  A tuple’s access level will be that of its most restrictive component.  So if one type is private, and the other is public, the tuple’s access control will be private.

A Tuple is a Value Type

var fullName = ("sandesh", "sardar")
var personFullName = fullName
personName.0 = "Harshal"
fullname.0  //output:  "sandesh"
personFullName.0  //output : "Harshal"

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Advertisements