Tuple in Swift
This article explains what a Tuple is and when and where it is used. Happy reading!!!
Tuple is a group of different values represented as one . According to apple, a tuple type is a comma-separated list of zero or more types, enclosed in parentheses. It’s a miniature version of a struct.
Let’s consider an example: A name say John smith can be declared as a tuple like ("John", "Smith")
. It holds the first and last name of a person. You can access the inner values using the dot(.
) notation followed by the index of the value:
var person = ("John", "Smith")
var firstName = person.0 // John
var lastName = person.1 // Smith
The type of a tuple is determined by the values it has. So
("tuple", 1, true)
will be of type(String, Int, Bool)
.
()
is the empty tuple – it has no elements. It also represents theVoid
type.Tuples don’t conform to the hashable protocol. Hence it cannot be used as dictionary keys.
Creating a tuple:
You can declare a tuple like any other variable or constant. To initialize it you will need a another tuple or a tuple literal. A tuple literal is a list of values separated by commas between a pair of parentheses. You can use the dot notation to change the…