Tuples in Swift allows user to assign group of values to a variable, constant and even return parameter of a function. In the below example, a employee constant is assigned Int and String values. And to access these parameters, we need to use .0 and .1

let employee = (103, “Deepak”)

employee.0

employee.1

Now let us say you want to assign proper name for these parameters so that you could access these values using those names instead of 0 and 1.

let employee = (id:103, name:“Deepak)

employee.id

employee.name

Here id and name are parameter names provided for employee id and employee name. You can also declare the data types for the tuple values like Int and String

let employee:(id:Int, name:String) = (102, “Deepak”)

employee.id

employee.name

Tuples and switch cases are powerful combination, look at an example below where Tuple has been used with switch cases. The _ is used for matching any values.

let employee:(id:Int, name:String) = (102, “Deepak”)

switch (employee) {

case (103105,_):

println(“developer”)

case (106108,_):

println(“tester”)

case (_,“Deepak”):

println(“CEO”)

default:

println(“Contractor”)

}


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.