Skip to content
AgileLogics
6 min read

Arrays

Prerequisites: for-in loops and ranges

An array is an ordered list of values of the same type.

Real-world analogy: an array is a numbered row of lockers. Each locker holds one item, and you find an item by its locker number.

Syntax

let fruits = ["apple", "banana", "cherry"]   // [String]
var scores: [Int] = []                       // an empty array of Int

Reading elements

Positions (indexes) start at 0:

let fruits = ["apple", "banana", "cherry"]

print(fruits[0])
print(fruits[2])
print(fruits.count)
print(fruits.isEmpty)
print(fruits.first ?? "none")
print(fruits.last ?? "none")
apple
cherry
3
false
apple
cherry

first and last return optionals because the array might be empty; fruits[0] doesn't, and crashes on an empty array.

Changing an array

The array must be a var:

var fruits = ["apple", "banana"]

fruits.append("cherry")
fruits.insert("apricot", at: 0)
fruits[1] = "avocado"
print(fruits)

let removed = fruits.removeLast()
print(removed)
fruits.remove(at: 0)
print(fruits)
fruits += ["date", "fig"]
print(fruits)
["apricot", "avocado", "banana", "cherry"]
cherry
["avocado", "banana"]
["avocado", "banana", "date", "fig"]

Arrays are values

Assigning an array to another variable makes an independent copy:

let original = [1, 2]
var copy = original
copy.append(3)
print(original)
print(copy)
[1, 2]
[1, 2, 3]

That's different from many languages, where both names would share one array. Swift's approach (called value semantics) prevents a whole category of bugs — Level 2 explains it in detail.

Common mistakes

  • Reading past the end: fruits[3] on a 3-element array is Fatal error: Index out of range. Check indices.contains(i), or use first/last.
  • Mixing types: [1, "two"] doesn't compile as a normal array.

Practice

Create an array of three cities, add a fourth, and print the list, the count, and the last city.

Show solution
var cities = ["Lagos", "Lima", "Oslo"]
cities.append("Tokyo")
print(cities)
print(cities.count)
print(cities.last ?? "none")