Workshop 17: TUPLE

 A tuple in swift is a collection containing values of varying types (Int, String, Double, Float, Bool) or the same type (Bool, Bool) . A Tuple element indices are zero-based. The first element of a non-empty tuple is always t(0).

Declare and Initialize a Tuple

You declare and initialize a tuple like this:

let employee = ("James Ford", 50, 4739.32, "photo003.jpg")
// Output in a playground file
(.0 "James Ford", .1 50, .2 4,739.32, .3 "photo003.jpg")

Access a Tuple Values

Once you’ve declared and initialize a tuple, you access its values by decomposing it. The first set of code decompose the tuple by using the tuple’s element indices. The second set of code decompose the tuple by using unique identifiers for each value.

//Decompose the tuple, method 1
// Output in a playground file
"James Ford"

//Decompose the tuple, method 2
let (name, age, salary, photo) = employee
//Output in a playground file
"James Ford"

If you want to ignore a tutple value when you decompose it, use the wildcard expression (_) instead of a name.

//Decompose only the last element of the tuple
let (_, _, _, empImage) = employee
//Output in a playground file

Give a Tuple Values a Name

When you declare a tuple, you can give each value a name. That way you can access them by using their names. Code below shows two ways to name a tuple values, when you declare and initialize it. The last statement shows how to access the tuple’s value by name.

var book = (author: String(), title: String(), instock: Bool()) = "Ann Rice"
book.title = "Lasher"
book.instock = true
// Output in a playground file
(.0 "", .1 "", .2 false)
"Ann Rice"

var book = (author: "Ann Rice", title: "Lasher", instock: true)
//Output in a playground file
(.0 "Ann Rice", .1 "Lasher", .2 true)

When to Use Tuples

Since a tuple is an ordered list of values, it can be used in place of multiple variables. For example; say you used three variables to store information about a book, you can replace them with a tuple. So, this:

var bookTitle = "Interview With The Vampire"
var bookAuthor = "Ann Rice"
var bookCategory = "Fiction"
var bookPrice = 7.99

becomes this:

 var bookObject = ("Interview With The Vampire", "Anne Rice", "Fiction", 7.99)

A tuple can be used as a function’s return value, in a Switch statement, when iterating an array, or a dictionary.