Arrays

Arrays are zero-based, and look like this:

let myArr = [21, 22, 23] 

They are equipped with a pretty standard set of methods, such as count and accessor methods:

let count = myArr.count // 3 
let secondElmt = myArr[1] // 22
let firstElmt = myArr.first // 21
let lastElmt = myArr.last // 23

Elements are set, logically enough, as follows:

myArr[1] = 100 

They are a lot more convenient to work with than NSArray:

let arr1 = [1,2] 
let arr2 = [3,4]
let arr3 = arr1 + arr2 // [1,2,3,4]

So, concatenating arrays is nice and simple, and this approach is reflected across the methods available on Swift's collection objects.

We can declare an Array object without initializing it, as follows:

var emptyArr1: [Int] 
var emptyArr2: Array<Int>

These two methods are equivalent.

We can declare and initialize an empty array at the same time with one of the following methods, which here, too, are all equivalent:

var emptyArr3 = [Int]() 
var emptyArr4: [Int] = []
var emptyArr5: Array<Int> = []

Once the type of Array is clear:

var myArr = [1,2,3]  

Here, myArr is initialized as an Array of Int type; we can set it to the empty array with just the empty brackets:

myArr = [] 

If we declare an Array object with let, we cannot change its values:

let constArr = [1,2,3] 
constArr[0] = 5

The second line will produce a compiler error.

If you are familiar with Swift's collection types, you'll know there's a lot more than this; but more of that later.