Sling Academy
Home/Swift/Swift: How to find the length of a given array

Swift: How to find the length of a given array

Last updated: April 17, 2023

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.

Next Article: Swift: How to append elements to an array

Previous Article: How to Compare 2 Arrays in Swift (Basic & Advanced)

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)