Skip to content

Arrays

An array stores multiple values of the same type in an ordered list.

Creating Arrays

swift
var fruits = ["Apple", "Banana", "Cherry"]
var emptyArray: [String] = []
var anotherEmptyArray = [String]() // Alternative way to create an empty array
var repeatedArray = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]

Accessing and Modifying

Arrays are 0-indexed.

swift
print(fruits[0]) // "Apple"

fruits.append("Date")
fruits += ["Elderberry"]
fruits[1] = "Blueberry" // Changing an element

Common Operations

OperationDescription
.countThe total number of elements.
.isEmptyChecks if the array has no elements.
.firstReturns the first element.
.lastReturns the last element.
.contains(_:)Checks if a specific value exists.
.append(_:)Adds a new element to the end.
.insert(_:at:)Adds a new element at a specific index.
.remove(at:)Removes the element at a specific index.
.removeAll()Empties the entire array.
.reversed()Returns the elements in reverse order.
swift
if !fruits.isEmpty {
    print("We have \(fruits.count) fruits.")
}

Sorting Arrays

It is important to understand the difference between modifying an array in place and creating a new sorted copy.

  • sort(): Sorts the original array directly. The array must be a variable (var).
  • sorted(): Leaves the original array unchanged and returns a completely new array containing the sorted elements.

Iterating over Arrays

swift
for fruit in fruits {
    print("I like \(fruit)")
}

If you need to work with both the item and its exact position, the enumerated() method is the best approach. It pairs each element with its index, making it highly effective for numbered lists.

swift
for (index, value) in fruits.enumerated() {
    print("Item \(index + 1): \(value)")
}

To loop through just the index numbers without accessing the underlying elements directly, use the indices property.

swift
for index in fruits.indices {
    print("Index position: \(index)")
}

NOTE

Arrays declared with let are immutable; you cannot add, remove, or change their elements.