Swift Arrays
An array stores an ordered list of values of the same type. Arrays are the collection you'll use most often in Swift: a list of messages, the songs in a playlist, the scores of a game.
Creating arrays
Write the values in square brackets. Swift infers the element type, or you can state it as [Type]:
let primes = [2, 3, 5, 7, 11] // [Int]
var names: [String] = ["Ana", "Ben"] // explicit type
var empty: [Double] = [] // empty array needs a type
let zeros = Array(repeating: 0, count: 4)
print(primes)
print(names)
print(empty.isEmpty, empty.count)
print(zeros)[2, 3, 5, 7, 11]
["Ana", "Ben"]
true 0
[0, 0, 0, 0]
An array declared with let is immutable: you can't add, remove or change elements. Use var when the array must change.
Accessing elements
Elements are numbered from 0. Use a subscript array[index], or the safe helpers first and last, which return an optional (nil for an empty array):
let planets = ["Mercury", "Venus", "Earth", "Mars"]
print(planets[0])
print(planets[2])
print(planets.count)
print(planets.first ?? "none")
print(planets.last ?? "none")
print(planets[1...2])Mercury
Earth
4
Mercury
Mars
["Venus", "Earth"]
Note: Reading an index that doesn't exist, such as
planets[10], crashes the program withFatal error: Index out of range. Checkindex < planets.count(or useindices.contains) when you aren't sure.
let planets = ["Mercury", "Venus"]
print(planets[5]) // 💥 Fatal error: Index out of rangeModifying arrays
var todo = ["Buy milk", "Write report"]
todo.append("Call mom") // add at the end
todo += ["Water plants", "Book flight"] // add several
todo.insert("Wake up", at: 0) // add at a position
todo[2] = "Write FINAL report" // replace
print(todo)
let removed = todo.remove(at: 1) // remove by index
print("Removed: \(removed)")
todo.removeLast()
print(todo)
print("Items left: \(todo.count)")["Wake up", "Buy milk", "Write FINAL report", "Call mom", "Water plants", "Book flight"]
Removed: Buy milk
["Wake up", "Write FINAL report", "Call mom", "Water plants"]
Items left: 4
Common array methods
| Method / property | Result |
|---|---|
count, isEmpty |
number of elements, whether it is empty |
contains(x) |
true if the value is in the array |
firstIndex(of: x) |
index of the first match (optional) |
sorted() / sort() |
sorted copy / sorts in place |
reversed() |
elements in reverse order |
min(), max() |
smallest / largest value (optional) |
joined(separator:) |
joins an array of strings into one string |
var scores = [72, 95, 88, 61, 95]
print(scores.contains(88))
print(scores.firstIndex(of: 95) ?? -1)
print(scores.sorted())
print(Array(scores.reversed()))
print(scores.min()!, scores.max()!)
scores.sort(by: >) // in place, largest first
print(scores)
let tags = ["swift", "ios", "beginner"]
print(tags.joined(separator: ", "))true
1
[61, 72, 88, 95, 95]
[95, 61, 88, 95, 72]
61 95
[95, 95, 88, 72, 61]
swift, ios, beginner
Looping over an array
let prices = [4.5, 3.0, 2.25]
var total = 0.0
for price in prices {
total += price
}
print("Total: \(total)")
for (i, price) in prices.enumerated() where price > 2.5 {
print("Item \(i) costs more than 2.5: \(price)")
}Total: 9.75
Item 0 costs more than 2.5: 4.5
Item 1 costs more than 2.5: 3.0
A where clause in a for-in loop filters which elements the body sees.
Arrays are values
Assigning an array to another variable makes an independent copy (Swift arrays are value types). Changing the copy leaves the original untouched:
var original = [1, 2, 3]
var copy = original
copy.append(4)
print("original: \(original)")
print("copy: \(copy)")original: [1, 2, 3]
copy: [1, 2, 3, 4]
Tip: Copies are cheap: Swift uses copy-on-write, so the actual memory is only duplicated when one of the arrays is modified.
Multidimensional arrays
An array can contain other arrays — useful for grids and tables:
let board = [
["X", "O", "X"],
[" ", "X", "O"],
["O", " ", "X"]
]
print(board[1][2]) // "O"Test yourself
What is the index of the first element in a Swift array?
- 1
- 0
- -1
- It depends on the type
What happens when you run let a = [1, 2]; print(a[2])?
- It prints nil
- It prints 0
- The program crashes: index out of range
- It prints 2
After var a = [1]; var b = a; b.append(2), what is a?
- [1, 2]
- [1]
- [2]
- []