Swift Arrays - Count and Element Positions

In this article, we'll explain how to work with the number of elements in a Swift Array and how to find the position of specific values.

Getting the Number of Elements with count

To get the number of elements in a Swift Array, use the count property.

let names = ["Smith", "Williams", "Miller", "Brown"]
print(names.count)

The output shows 4 because there are four elements in the array.

4

Checking if an Array is Empty with isEmpty

To check whether a Swift Array is empty, use the isEmpty property.

var names = ["Smith", "Williams", "Miller", "Brown"]
print(names.isEmpty)

names.removeAll()
print(names.isEmpty)

Here is the result. After calling removeAll(), the array becomes empty and names.isEmpty returns true.

false
true

Finding Positions with firstIndex() and lastIndex()

To find the index of the first occurrence of a value in a Swift Array, use the firstIndex() method.

If the specified value is not found, the method returns nil.


For example, to find the index of the first occurrence of "Miller" or "Johnson" in the following array, you can write the code as follows.

Here, we also use ?? to provide a default value "Not Found" when the result is nil.

let names = ["Smith", "Williams", "Miller", "Brown", "Miller"]

print(names.firstIndex(of: "Miller") ?? "Not Found")
print(names.firstIndex(of: "Johnson") ?? "Not Found")

The output shows that "Miller" first appears at index 2, while "Johnson" does not exist in the array and returns "Not Found".

2
Not Found

Similarly, to get the index of the last occurrence of a value in the array, use the lastIndex() method.

let names = ["Smith", "Williams", "Miller", "Brown", "Miller"]

print(names.lastIndex(of: "Miller") ?? "Not Found")
print(names.lastIndex(of: "Johnson") ?? "Not Found")

The result shows that "Miller" last appears at index 4, while "Johnson" is not found in the array.

4
Not Found

Checking for an Element with contains()

To check whether a specific element exists in a Swift Array, use the contains() method.

For example, to check whether the names array contains "Miller" or "Johnson", you can write the code as follows.

let names = ["Smith", "Williams", "Miller", "Brown", "Miller"]

print(names.contains("Miller"))
print(names.contains("Johnson"))

The output shows true because "Miller" exists in the array, and false because "Johnson" does not.

true
false

That's it for working with the number of elements in a Swift Array and finding the position or existence of specific values.