Skip to content
DeveloperMemos

Getting the Size of a List/Array in Swift

Swift, iOS Development, Arrays, Lists1 min read

When working with lists or arrays in Swift, it's common to need the size or count of the elements. Knowing the size is crucial for iterating over the elements, performing calculations, or handling data dynamically. In this article, we will explore different approaches to getting the size of a list/array in Swift.

Using the count Property

The simplest and most straightforward way to determine the size of an array or list in Swift is by using the built-in count property. The count property returns the number of elements present in the collection.

1let numbers = [1, 2, 3, 4, 5]
2let size = numbers.count
3
4print("Size of the array: \(size)") // Output: Size of the array: 5

In the above example, we have an array numbers containing five integers. We use the count property to retrieve the size of the array, which is then printed to the console.

Using the isEmpty Property

Another useful property when determining the size of an array or list is isEmpty. This property returns a Boolean value indicating whether the collection is empty or not. By combining isEmpty with an if statement, we can conditionally handle cases where the collection has no elements.

1let fruits = ["apple", "banana", "orange"]
2
3if fruits.isEmpty {
4 print("The list is empty.")
5} else {
6 let size = fruits.count
7 print("Size of the list: \(size)") // Output: Size of the list: 3
8}

In this example, we have an array fruits that contains three string elements. The isEmpty property is used to check if the array is empty. If it's not empty, we retrieve the size using the count property and print it accordingly.

Using a for-in Loop

When you need to perform additional operations while iterating over the elements of a list/array, using a for-in loop can be beneficial. By utilizing a loop, you have the flexibility to access each element individually and perform custom logic as needed. Additionally, you can manually keep track of the count while iterating through the elements.

1let scores = [85, 90, 92, 87, 89]
2var count = 0
3
4for _ in scores {
5 count += 1
6}
7
8print("Size of the array: \(count)") // Output: Size of the array: 5

In this example, we have an array scores representing test scores. By using a for-in loop and incrementing the count variable for each element, we manually calculate the size of the array.

Conclusion

Obtaining the size of a list/array is essential for various programming tasks. In this article, we explored different methods to get the size of a list/array in Swift. We used the count property to directly retrieve the size, checked if the collection was empty using the isEmpty property, and employed a for-in loop to manually iterate and calculate the size. These techniques provide flexibility based on your specific requirements.