Tuples in Carbon are immutable ordered collections of values. They are similar to arrays but have a fixed size and can contain elements of different data types. Tuples are often used to group related data together.
Creating Tuples
Tuples are created using parentheses ()
, with elements separated by commas. The data type of each element is inferred from its value.
Code snippet
var myTuple: (int, string, bool) = (10, "Hello", true);
Accessing Elements
Elements in a tuple are accessed using their index, starting from 0.
Code snippet
var firstElement: int = myTuple.0;
var secondElement: string = myTuple.1;
var thirdElement: bool = myTuple.2;
Tuple Destructuring
Tuple destructuring allows you to extract elements of a tuple into individual variables.
Code snippet
var (a, b, c) = myTuple;
Tuple Methods
Tuples have several methods:
count()
: Returns the number of elements in the tuple.dropFirst()
: Returns a new tuple without the first element.dropLast()
: Returns a new tuple without the last element.isEmpty()
: Returnstrue
if the tuple is empty,false
otherwise.startIndex()
: Returns the starting index of the tuple.endIndex()
: Returns the ending index of the tuple.
Example
Code snippet
var person: (string, int, bool) = ("Alice", 30, true);
print("Name: \(person.0)");
print("Age: \(person.1)");
print("Is employed: \(person.2)");
var (name, age, isEmployed) = person;
print("Name: \(name)");
print("Age: \(age)");
print("Is employed: \(isEmployed)");
Use Cases for Tuples
Tuples are often used for:
- Returning multiple values from a function.
- Representing structured data, such as coordinates or database records.
- Passing arguments to functions that require multiple values.
Tuples are a versatile and efficient data structure in Carbon, providing a convenient way to group and manipulate related data.