We've seen how arrays hold collections of elements, and how we can add (.append()
) or remove (.removeFirst()
, .removeLast()
) elements.
But how can we easily find out exactly how many elements are currently inside an array.
Engagement Message
Any ideas?
As you might've already guessed each array has a count (or size), which is simply the number of elements it contains.
An array like [10, 20, 30]
has three elements. An empty array []
has zero elements.
Engagement Message
Does the count change when we append or remove elements?
Swift provides a built-in property called .count
to get the number of elements in an array. It's different from a function - you access it directly on the array.
You use it like this: yourArray.count
. You just add .count
after the array variable name.
Engagement Message
What kind of value do you expect .count
to give back?
The .count
property returns an integer representing the number of elements.
