Google News
logo
Swift - Interview Questions
What is Tuple in Swift?
In Swift, a tuple is a group of different values. And, each value inside a tuple can be of different data types.
 
Suppose we need to store information about the name and price of a product, we can create a tuple with a value to store name (string) and another value to store price (float)
 
Create A Tuple : In Swift, we use the parenthesis () to store elements of a tuple. For example,
var product = ("MacBook", 1099.99)​
Here, product is a tuple with a string value Macbook and integer value 1099.99.
 
Access Tuple Elements : Like an array, each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index 0.
 
We use the index number to access tuple elements. For example,
// access the first element
product.0

// access second element
product.1
Example : Swift Tuple
// create tuple with two elements
var product = ("MacBook", 1099.99)

// access tuple elements
print("Name:", product.0)
print("Price:", product.1)
Output :
Name: MacBook
Price: 1099.99
Advertisement