Swift Array count

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

Example

var languages = ["Swift", "C", "Java"]

// count total number of elements in languages var result = languages.count
print(result) // Output: 3

count Syntax

The syntax of the array count property is:

array.count 

Here, array is an object of the Array class.


count Return Values

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


Example 1: Swift Array count

var names = ["Gregory", "Perry", "Nadal"]

// count total elements on names print(names.count)
var employees = [String]()
// count total elements on employees print(employees.count)

Output

3
0

In the above example, since

  • names contain three string elements, the property returns 3.
  • employees is an empty array, the property returns 0.

Example 2: Using count With if...else

var numbers = [1,2,3,4,5,6,7,8,9,10]

// true because there are 10 elements on numbers if (numbers.count > 5) {
print( "The array size is large") } else { print("The array size is small") }

Output

The array size is large

In the above example, we have created the array named numbers with 10 elements.

Here, since there are 10 elements in the array, numbers.count > 5 evaluates to true, so the statement inside the if block is executed.

Did you find this article helpful?