Arrays (swift)

In Swift, arrays are implemented as structs, making them value types rather than reference types (i.e., classes). When a value type is assigned to a variable as an argument to a function or method, a copy is created and assigned or passed.

Let’s take a look at an example of an Array

Here we have a basic Array, which is of type [String].

The square brackets indicate that this is an array of String objects, rather than just being a single String. As usual, Swift can infer this type data too, just by examining the initial assignment:

We can access elements of this array in a variety of ways, such as using an Int index, calling the various collections methods.

print( starks[0] )
print( starks[2] )
print( starks.first! ) //if starks.first is optional and has a value, unwrap optional and expose the value
Robb
Arya
Robb

Searching for item in array

not found returns nil
found returns the index

If you try to access an index in an array that is not present, your program will fail at runtime! So always check the length of arrays when accessing by index:

Accessing a non-existing element will crash