Collections and functions
Arrays in Swift
An introduction to arrays in Swift: how to declare and type them, access items, and use methods like append, insert, remove, count, isEmpty, and sort.
This tutorial belongs to the Swift series
An array is an ordered collection of items. It’s the collection you’ll reach for most often.
Here we create an array holding 3 integers:
var list = [1, 2, 3]
You access the first item with list[0], the second with list[1], and so on. Positions start at 0, like in most languages.
Arrays have one type
All the elements in a Swift array must have the same type. [1, 2, 3] is an array of Int, and you can’t put a string in it.
When you initialize the array with values, Swift infers the type, as in the example above.
For an empty array there’s nothing to infer from, so you declare the type yourself:
var list: [Int] = []
Another shorthand for the same thing:
var list = [Int]()
You can also spell out the type even when you have values:
var list: [Int] = [1, 2, 3]
A quick way to build an array of consecutive numbers is to pass a range to Array():
var list = Array(1...4) // [1, 2, 3, 4]
Counting items
count tells you how many items the array holds:
var list = [1, 2, 3]
list.count // 3
isEmpty is true when there are no items:
var list = [1, 2, 3]
list.isEmpty // false
Use isEmpty instead of count == 0. It reads better and says what you mean.
Adding items
append() adds an item at the end:
var list: [Int] = [1, 2, 3]
list.append(4) // [1, 2, 3, 4]
insert(_:at:) puts an item at any position:
var list: [Int] = [1, 2, 3]
list.insert(17, at: 2)
// list is [1, 2, 17, 3]
An array must be declared with
varto be modified. If you declare it withlet, you can’t add or remove elements. The compiler tells youCannot use mutating member on immutable value.
Removing items
remove(at:) removes the item at a given index:
var list: [Int] = [1, 2, 3]
list.remove(at: 1)
// list is [1, 3]
Be careful with the index. Removing at an index that doesn’t exist, like list.remove(at: 5) on a 3-item array, crashes the program with Fatal error: Index out of range. Check count first if the index comes from user input.
removeLast() and removeFirst() are two handy shortcuts for the last and the first element.
To remove everything, call removeAll() or assign an empty array:
var list: [Int] = [1, 2, 3]
list.removeAll()
// or
list = []
Sorting
sort() sorts the array in place:
var list = [3, 1, 2]
list.sort()
// list is [1, 2, 3]
There are a lot more methods, but these are the ones you’ll use every day.
Equality and copies
Two arrays are equal when they contain the same elements, in the same order:
[1, 2, 3] == [1, 2, 3] // true
Arrays are value types. When you pass an array to a function, return it from a function, or assign it to another variable, Swift copies it. Changes to the copy don’t touch the original.
Arrays are collections, so you can loop over them with for-in, as we saw in the loops lessons.
Lesson completed