Tuples in Swift

We can group different values into a single value. What can possibly go wrong?

Steven Curtis

--

Tuples in Swift allows you to store multiple values in a single variable. Since we a representing multiple values as a single variable, it only really makes sense if the constituent parts are tightly connected.

Photo by Evelyn on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)

Terminology

Data Types: A representation of the tyoe of data that can be processed, for example Integer or String

Tuple: A way in Swift to allow you to store multiple values in a single variable.

Storing multiple values

Using a Struct

One possible solution to storing multiple values is to use a Struct

struct Person {
var name: String
var age: Int
}
let steve = Person(name: "Steve", age: 22)

Now, as you can see this is quite long and verbose. That is not to say that there are not uses for creating a Class or a Struct to store this data — but like many things in programming this is a question of style and taste.

Now of course a struct can also conform to protocols and methods can be written within the structure so really flexibility is one of the keys here.

The struct needs to be created in code, so you would need to know what data needs to be stored ahead of time.

Using an Array

You might want to use an array to store the details about a person.

However you can’t mix types in an Array

let steve = ["Steve", 22] // Error

So one alternative is to store the elements as Strings, and the elements can be written out by indexing them:

let steve = ["Steve", "22"]
print (steve) // ["Steve", "22"]
print (Steve[0]) // "Steve"

This isn’t great if we want to store more complex data types.

--

--