• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips
You are here: Home / Apple / Tuples in Swift

Tuples in Swift

January 13, 2015 By Ravi Shankar Leave a Comment

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 (103…105,_):

println(“developer”)

case (106…108,_):

println(“tester”)

case (_,“Deepak”):

println(“CEO”)

default:

println(“Contractor”)

}

Filed Under: Apple, ios, iPad, iPhone, Programming Tagged With: Apple, iPad, Switch, Tuples

Reader Interactions

Leave a Reply Cancel 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.

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy