To get the element of an array at a specific index, the indexing syntax can be used: The array is followed by an opening square bracket [, the indexing value, and ends with a closing square bracket ].
Indexes start at 0 for the first element in the array.
Accessing an element which is out of bounds results in a fatal error at run-time and aborts the program.
// Declare an array of integers.
let numbers = [42, 23]
// Get the first number of the array.
//
numbers[0] // is `42`
// Get the second number of the array.
//
numbers[1] // is `23`
// Run-time error: Index 2 is out of bounds, the program aborts.
//
numbers[2]
// Declare an array of arrays of integers, i.e. the type is `[[Int]]`.
let arrays = [[1, 2], [3, 4]]
// Get the first number of the second array.
//
arrays[1][0] // is `3`
To set an element of an array at a specific index, the indexing syntax can be used as well.
// Declare an array of integers.
let numbers = [42, 23]
// Change the second number in the array.
//
// NOTE: The declaration `numbers` is constant, which means that
// the *name* is constant, not the *value* – the value, i.e. the array,
// is mutable and can be changed.
//
numbers[1] = 2
// `numbers` is `[42, 2]`