This short and straightforward article shows you a couple of different ways to find the length of a given array in Swift.
The easiest approach is to use the count property on the array. This property returns the number of elements in the array.
Example:
var numbers = [1, 2, 3, 4, 5]
var length = numbers.count
print("The length of the array is \(length)")
Output:
The length of the array is 5
Another way to find the length of an array is to use a for loop and increment a variable for each element in the array.
Example:
var fruits = ["apple", "banana", "orange"]
var length = 0
for _ in fruits {
length += 1
}
print("There are \(length) fruits in the basket.")
Output:
There are 3 fruits in the basket.
In my opinion, this approach is more verbose than necessary, and there is no reason to use it in production projects.