Swift Language Accessing Array Values


Example

The following examples will use this array to demonstrate accessing values

var exampleArray:[Int] = [1,2,3,4,5]
//exampleArray = [1, 2, 3, 4, 5]

To access a value at a known index use the following syntax:

let exampleOne = exampleArray[2]
//exampleOne = 3

Note: The value at index two is the third value in the Array. Arrays use a zero based index which means the first element in the Array is at index 0.

let value0 = exampleArray[0]
let value1 = exampleArray[1]
let value2 = exampleArray[2]
let value3 = exampleArray[3]
let value4 = exampleArray[4]
//value0 = 1
//value1 = 2 
//value2 = 3
//value3 = 4
//value4 = 5

Access a subset of an Array using filter:

var filteredArray = exampleArray.filter({ $0 < 4 })
//filteredArray = [1, 2, 3]

Filters can have complex conditions like filtering only even numbers:

var evenArray = exampleArray.filter({ $0 % 2 == 0 })
//evenArray = [2, 4]

It is also possible to return the index of a given value, returning nil if the value wasn't found.

exampleArray.indexOf(3) // Optional(2)

There are methods for the first, last, maximum or minimum value in an Array. These methods will return nil if the Array is empty.

exampleArray.first // Optional(1)
exampleArray.last // Optional(5)
exampleArray.maxElement() // Optional(5)
exampleArray.minElement() // Optional(1)