Swift - Data Type Arrays

Introduction

Arrays are contiguous ordered lists of values.

Swift creates an array using square brackets []:

let intArray = [1,2,3,4,5] 

This creates an array of ints.

Swift type inference system determines it to be an array of integers because that is the only type inside the array.

To be explicitly typed:

let explicitIntArry  : [Int] = [1,2,3,4,5] 

To get elements out of an array we use their index and the subscript operator:

intArray[2] // 3 

Arrays in Swift start at position 0.

int at index 2 were actually the third element in the array.

If we attempt to access an element beyond the range of the array, Swift will throw an error:

intArray[-1] // this will error if we try and run it 

To modify an array we need to declare it as mutable first:

var mutableArray = [1,2,3,4,5] 

To add elements to and remove elements from this array, and we can do so in a variety of ways:

// append elements to the end of the array 
mutableArray.append(6) // [1, 2, 3, 4, 5, 6] 
// remove elements at a specific index 
mutableArray.remove(at: 2) // returns 3, array now holds [1, 2, 4, 5, 6] 
// replace elements at a specific index 
mutableArray[0] = 3 // returns 3, array now holds [3, 2, 4, 5, 6] 
// insert elements at a specific index 
mutableArray.insert(3, at: 2) // array now holds [3, 2, 3, 4, 5, 6] 

To declare an empty array in preparation for later use:

var emptyArray = [Int]() 
// this will create an empty Int array 
emptyArray.append(0) // [0] 

To know how many elements are inside the array, you can use the count property:

// returns the number of elements in the array 
intArray.count // 5 

Related Topics

Exercise