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, the second using
list 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
var list = [1, 2, 3] list.count //3
If an array is empty, its
isEmpty property is
var list = [1, 2, 3] list.isEmpty //false
You can append an item at the end of the array using the
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
varto 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]
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 = 
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.