Skip to content

Arrays in Swift

New Course Coming Soon:

Get Really Good at Git

This tutorial belongs to the Swift series

We use arrays to create a collection of items.

In this example we create an array holding 3 integers:

var list = [1, 2, 3]

We can access the first item using the syntax list[0], the second using list[1] and so on.

Elements in an array in Swift must have the same type.

The type can be inferred if you initialize the array at declaration time, like in the case above.

Otherwise the type of values an array can include must be declared, in this way:

var list: [Int] = []

Another shorthand syntax is:

var list = [Int]()

You can also explicit the type at initialization, like this:

var list: [Int] = [1, 2, 3]

A quick way to initialize an array is to use the range operator:

var list = Array(1...4) //[1, 2, 3, 4]

To get the number of items in the array, use the count property:

var list = [1, 2, 3]
list.count //3

If an array is empty, its isEmpty property is true.

var list = [1, 2, 3]
list.isEmpty //false

You can append an item at the end of the array using the append() method:

var list: [Int] = [1, 2, 3]
list.append(4)

or you can an item at any position of the array using insert(newElement: <Type> at: Int):

var list: [Int] = [1, 2, 3]
list.insert(17, at: 2)
//list is [1, 2, 17, 3]

An array must be declared as var to be modified. If it’s declared with let, you cannot modify it by adding or removing elements.

To remove one item from the array, use remove(at:) passing the index of the element to remove:

var list: [Int] = [1, 2, 3]
list.remove(1)
//list is [1, 3]

removeLast() and removeFirst() are two handy ways to remove the last and first element.

To remove all items from the array, you can use removeAll() or you can assign an empty array:

var list: [Int] = [1, 2, 3]
list.removeAll()
//or
list = []

The sort() method sorts the array:

var list = [3, 1, 2]
list.sort()
//list is [1, 2, 3]

There are a lot more methods, but those are the basic ones.

Arrays are equal when they contain the same elements, of the same type:

[1, 2, 3] == [1, 2, 3] //true

Arrays are passed by value, which means if you pass an array to a function, or return it from a function, the array is copied.

Arrays are collections, and they can be iterated over in loops.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my Swift Handbook

Here is how can I help you: