Chapter    8

Tuples

Tuples are ordered lists of values. In Swift, you can group related elements together as a tuple, reducing the need to depend on complex types, objects, and immutable arrays.

Listing 8-1 shows how you would declare a tuple for a rectangle.

Listing 8-1. Declaring Tuples

let rectangle1 = (0, 0, 200, 100)

In Listing 8-1, you use the let keyword to declare a constant and give the constant the name rectangle1. After the assignment operator (=), you supply a comma-separated list of values enclosed in parentheses.

The value of rectangle1 from Listing 8-1 would be (0, 0, 200, 100).

For greater clarity, you can annotate each value in the tuple list as shown in Listing 8-2.

Listing 8-2. Annotated Tuple

var rectangle2 = (x:0, y:0, width:200, ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.