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 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

  • .count: Number of elements.
  • .isEmpty: Checks if array is empty.
  • .remove(at:): Removes element at specific index.
  • .contains(): Checks for existence of a value.
swift
if !fruits.isEmpty {
    print("We have \(fruits.count) fruits.")
}

Iterating over Arrays

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

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

NOTE

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