How to find size of an array in Swift

In this tutorial, we are going to learn how to find the size of an array in Swift.

There are two ways to get the total number of elements in the array. They are:

  • Using count property
  • Using for loop

Let us understand each of them in a simple way.

Using count property to find array size in Swift

The swift array has a built-in property that gives the size or the total number of elements in an array known as count. It is just a property so it doesn’t need any brackets or parameters like a method.

It returns the size of an array as an integer value and that value can be stored in some variable.

Syntax:
arr.count

Swift program to find the size of an array using count property

let arr = [1,2,3,4,5,6,7,8]
var size = arr.count
print(size)

Output:

8

In the above code, we declared an array arr. Then we found the array size using the count property and stored it in a variable called size. At last, we printed the size of an array.

Using for loop

We can also find the array size by using a simple for loop. First of all, we need to declare and initialize a counter variable with 0. Then by traversing through the array, we will increment the value of the counter variable by 1 for each iteration.

As a result, at the end of the loop, the counter variable will have the size of an array.

Swift program to find the size of an array using for loop

let arr = [1,2,3,4,5,6,7,8]
var counter = 0
for i in arr{
    counter += 1
}
print(counter)

Output:

8

In the above code, we declared an array arr and initialized a counter variable with 0. Then for each element of an array, we incremented the count of the counter variable. Finally, we printed the size of the array using that stored in a counter variable.

That’s it! Hope you understood the tutorial.

Also, do check our other related articles,

Leave a Reply

Your email address will not be published.