O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Counting the elements of an array

At times, it is essential to know the number of elements in an array. The array type in Swift contains a read-only count property. The following example shows how to use this property to retrieve the number of elements in both single-dimensional and multidimensional arrays:

let arrayOne = [1,2,3] 
let multiArrayOne = [[3,4],[5,6],[7,8]]  
print(arrayOne.count)  //Displays 3 
print(multiArrayOne.count)  //Displays 3 for the three arrays  
print(multiArrayOne[0].count)  //Displays 2 for the two elements 

The value that is returned by the count property is the number of elements in the array and not the largest valid index of the array. For nonempty arrays, the largest valid index is the number of elements in the array ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required