Home > Articles > Data > SQL Server

Swift Development: Nobody Knows the Tuples I've Seen

  • Print
  • + Share This
In the Swift programming language, tuples play specialized roles that lend power and flexibility to your development. Erica Sadun, bestselling author of The Gourmet iOS Developer's Cookbook: Even More Recipes for Better iOS App Development, explores tuples in depth.
Like this article? We recommend

In Swift, as in many other modern languages, finite ordered lists called tuples group items together into single units. The Swift version of tuples appears in parentheses as a sequence of comma-separated elements.

Tuples may look a bit like arrays, but a tuple creates a syntactically distinct construct. What's the difference between the two? A tuple is a fixed-length vector containing varying types; an array is an ordered collection of data that shares a unifying type.

Tuples as Structs

Tuples are essentially anonymous structures. Like standard structs, tuples allow you to combine types in an addressable fashion. A tuple of (1, "Hello", 2.4) is more or less equivalent to the following struct instance:

struct MyStruct {
    var a: Int
    var b: String
    var c: Double
let mystruct = MyStruct(a: 1, b: "Hello", c: 2.4)

But wait, you say. That (1, "Hello", 2.4) tuple doesn't have names, and the struct does. You access tuple fields with .0, .1, .2, and the struct fields with .a, .b, .c.

In fact, Swift allows you to add labels to tuples. For example, (a:1, b:"Hello", c:2.4) is a perfectly acceptable tuple:

let labeledTuple = (a:1, b:"Hello", c:2.2)
labeledTuple.1 // "Hello"
labeledTuple.b // "Hello"

When a tuple is defined using labels, you access it both by ordered fields (.0, .1, .2) and label fields (.a, .b, .c). The opposite is not true. You cannot refer to a structure by field order.

It's a pity that Swift doesn't offer a grand unified structure/tuple/class type. These things seem more alike than different to me, and simpler universal concepts would add nicely to the language's elegance. However, people familiar with Swift assure me that there are compelling reasons this has not happened.

  • + Share This
  • 🔖 Save To Your Account