Tuple /ˈtjʊpəl; ˈtʌpəl/

noun (TUH-pul)

1. In programming languages, such as Lisp, Python, Linda, and others, a tuple is an ordered set of values.

At their core, tuples group multiple values into a single compound return type. They are intrinsically flexible, allowing any type (reference or value) to be contained within them. They tend to shine in scenarios where one needs to be intentional about a return type, yet the situation is too small or “one off” to create a wrapper class to do so.

Observe:

let http404Error = (404, “Not Found”)

This is Apple’s favorite use case to show off Tuples. Here, the tuple would return one compound type containing an Int and a String. When referring to such a type, it is semantically accurate to refer to it as a “tuple of type (Int, String)”.

Accessing Values

Decomposing a tuple refers to the method in which you access its values. Let us veer away from Apple’s demonstration and look at one straight from the real world:

class func setDetailsForCellAtIndexPath(idp:NSIndexPath) -> (text:String?, detailText:String?, image:UIImage?)

{

let cellText = AccountsTableViewHelper.getCellText(idp)

let image = AccountsTableViewHelper.getCellImage(idp)

return (cellText.text, cellText.detailText, image?)

}

This simplistic function helps solve the problem of the no-relation table view. You’ve seen these table views before, they exhibit signs of information that do not relate to one another in any fashion (i.e. “Rate App” and “Visit Us Online”).

Tuples help solve this particular scenario rather nicely. Instead of creating a wrapper class to return an object with information each cell needs, a tuple is created with the cell’s text, detail text, and an image — if applicable.

To decompose the value(s), we use syntax that mimcs that of accessing a first class object’s members:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

{

var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(REUSE_ID) as?UITableViewCell

var cellDetails = AccountsTableViewHelper.setDetailsForCellAtIndexPath(indexPath)



//Decompose tuple for cell's data

cell!.textLabel?.text = cellDetails.text

cell!.detailTextLabel?.text = cellDetails.detailText

cell!.imageView?.image = cellDetails.image return cell!

}

You can also be selective about which values you care about in a tuple. For instance, suppose there was a cell which did not require an image. These situations are tastefully handled by inserting _ where the parameter you wish to ignore is:

var cellDetails = AccountsTableViewHelper.setDetailsForCellAtIndexPath(indexPath) let (text, detailText, _) = cellDetails

Going further, you can decompose a tuple using Array syntax as well: