Swift Arrays

Arrays in Swift are ordered, type-safe collections that let you store multiple values of the same type under a single name.

Declaring an Array

Swift arrays are written with the shorthand syntax [Type], meaning an array that holds values of that specific type. Because Swift is statically typed, once an array is created to hold Int values, you cannot insert a String into it. This type safety is enforced at compile time, catching mistakes long before your app ever runs.

Creating arrays

var scores: [Int] = [88, 92, 76, 100]
var names = ["Ravi", "Meera", "John"] // type inferred as [String]
var empty: [Double] = []

print(scores)
print(names)
print(empty.isEmpty)

Accessing and Modifying Elements

Array elements are accessed using zero-based subscript indexing, so the first element sits at index 0. Attempting to read an index that is out of bounds will crash your program at runtime, so always check count before indexing dynamically computed positions. Arrays declared with var are mutable, meaning you can change, add, or remove elements after creation; arrays declared with let are fixed and cannot be resized.

Reading and updating values

var fruits = ["apple", "banana", "cherry"]
print(fruits[0])          // apple

fruits[1] = "blueberry"   // replace an element
fruits.append("date")     // add to the end
fruits.insert("mango", at: 0)

print(fruits)             // [mango, apple, blueberry, cherry, date]
print(fruits.count)       // 5

Common Array Methods

Swift's standard library equips arrays with a rich set of methods for searching, transforming, and removing elements. Rather than writing manual loops for everyday tasks, you can reach for built-ins that are both more concise and less error-prone.

  • append(_:) adds a single element to the end of the array
  • remove(at:) deletes the element at a given index and returns it
  • contains(_:) returns true if the array holds a matching value
  • sorted() returns a new array with elements in ascending order
  • reversed() returns the elements in reverse order as a sequence
  • firstIndex(of:) returns the index of the first matching element, or nil

Using common methods together

var numbers = [5, 3, 9, 1, 3]

numbers.removeAll { $0 == 3 }   // removes every 3
print(numbers)                  // [5, 9, 1]

let sorted = numbers.sorted()
print(sorted)                   // [1, 5, 9]

print(numbers.contains(9))      // true
print(numbers.firstIndex(of: 9) ?? -1) // 1

Iterating and Transforming

A for-in loop is the simplest way to visit every element, but Swift also offers functional operators like map, filter, and reduce that transform an array without mutating the original. These operators are chainable, so you can express multi-step pipelines in a single readable expression.

Note: Prefer map/filter/reduce over manual loops when you are producing a new array from an existing one — the intent reads more clearly and there is less room for off-by-one bugs.
Note: Arrays in Swift are value types. Assigning an array to a new variable or passing it to a function copies its contents (with copy-on-write optimization), so mutations inside a function do not affect the caller's array unless it is passed with inout.

Multidimensional Arrays

Swift does not have a dedicated matrix type, but you can nest arrays inside arrays to model grids, boards, or tables. Each inner array is fully independent, so rows can even have different lengths, although in practice you usually keep them uniform.

A simple 3x3 grid

var grid: [[Int]] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(grid[1][2])   // 6, row 1 column 2

for row in grid {
    print(row.map(String.init).joined(separator: " "))
}
MethodReturnsMutates original?
append(_:)VoidYes
sorted()New [Element]No
sort()VoidYes
filter(_:)New [Element]No
remove(at:)Removed elementYes

Exercise: Swift Arrays

How is an array of String values written as a type in Swift?