In this tutorial, you are going to learn how to count the number of elements of a specific Tuple in Swift with example code.
Swift already comes with a built-in Mirror that can help us to count the number of tuple elements. The
Mirror helps us to query any kind of data in our Swift code.
Let’s see an example below to perform our task:
let numbersTuple = (5,6,7,8,9) let tupleSize = Mirror(reflecting: numbersTuple).children.count // Print tuple size print(tupleSize)
As we can see in the above code, we are able to print the size of the tuple. The variable tupleSize stores the size of the tuple. The size refers to the number of tuple items.
We have first created a tuple and stored it inside the variable
numbersTuple. After that, we get the reflection of our tuple using Swift
In our example, we are using the
count method to count the number of tuple elements. The count method can be used to get the size of other collection types also.
We have successfully been able to get the number of tuple items just within two lines of code.