Count array elements in Swift


In this Swift programming tutorial, you are going to learn how to count the number of elements of an array with examples.

Getting the size of a Swift array is quite easy. Actually Swift made it easy for us by providing the count property.

The count property of Swift returns the number of elements present in an array.

Below is given how we can use the count property:

var colors = ["Red", "Yellow", "Green", "Black"]

// count the total number of elements in colors
var totalElements = colors.count

print(totalElements)

Output:

4

The syntax of the Array count property is so simple like you can see below:

array.count

In the above syntax, the array is our object of the Array class and count is the property provided by Swift.

Example 1

Below is another example:

var fruits = ["Apple", "Mango", "Banana", "Pear"]

// count elements of fruits
print(fruits.count)

var countries = [String]()

// total elements of countries
print(countries.count)

Output:

4
0

In the above code, the fruits has 4 elements, so the count property return 4. On the other hand, the countries is empty, so using count property on its returns 0.

Example 2: Using count property with if…else statement

In real-world projects like iOS app development or app development for any type of Apple device, it is often useful to use the array count property with the Swift if...else statement. So below is an example of using the count property with the if…else statement:

var fruits = ["Apple", "Mango", "Banana", "Pear"]

if (fruits.count < 6) {
    print("Small array")
} else {
    print("Large array")
}

Output:

Small array

The above code executes the code inside the if statement as the number of elements present in the array is 4, which is less than 6.

In our if...else statement, we are checking if the total number of elements in the array is less than 6 or not.