In Swift, you have many kinds of data.
Each kind or category of data is called a type
.
You’ve seen types
in action in variable declarations:
let myString: String
let myInt: Int
In this example above, we’re saying create a variable called myString
that is a String
type
. Then create another variable called myInt
that is an integer type
.
There exists a type
called tuple
.
A tuple
is made up of many pieces of data, where each piece of data can be of a different type
.
In this declaration below, we create a tuple
that contains a String
type
and also an integer type
:
let myTuple: (String, Int) = ("Vincent", 25)
If you want to access one of the values within the tuple, you can use dot notation and refer to the index of the item you want:
let myTuple = ("Vincent", 25)
print("\(myTuple.0) looks \(myTuple.1) years old.")
// Output:
Vincent looks 25 years old.
If you want to be more explicit, though, you can name the items in a tuple. Then you can refer to their names instead of their indexes:
let myTuple = (name: "Vincent", age: 25)
print("\(myTuple.name) looks \(myTuple.age) years old.")
// Output:
Vincent looks 25 years old.
When should I use it?
A good use case for a tuple
is when you want to return two pieces of data, of different types
, from a method:
func getPersonalInformation() -> (name: String, age: Int) {
return (name: "Vincent", age: 25)
}
This makes it easy to use the pieces of information separately when you call the method:
let (name, age) = getPersonalInformation()
print("I only need the name for now: \(name)")
// Output:
I only need the name for now: Vincent
Conclusion
A tuple
is a type
that contains other types
. It makes it easy to return multiple values from a function or method. Elements of a tuple can be referenced by a name, or by an index.