Arrays in Swift

Become a Subscriber

Note: Video is part of a Swift beginner series by MadApper (a.k.a. Paul Napier)

Arrays are an ordered list of objects or variables. There are both mutable and immutable array types (NSArray, NSMutableArray). In Swift, while we can use the NS-prefixed types, we recommend using the Array type at all times. Let’s declare some array variables:

var array1:Array = []
//explicit Array declaration
var array2 = []
//implicit Array declaration

The square brackets tell the compiler our variables are arrays. So if we create an array of integers, the compiler knows our variable is an array of integers:

var array2 = [10,5,6,89]

In the above example, we’ve actually implicitly declared the type of the array objects we expect (in this case, integers). We can also explicitly declare the type of objects in our array:

var array2:Array = [10,5,6,89]

If we now tried to add a object that is not of the type we explicitly declared our array object so to be, we’d get an error.

var array2:Array = [10,5,6,89, ""]
//error: type 'Int' does not conform to protocol 'StringLiteralConvertible'

The error we got is telling us that Swift is trying to take our string object and convert it into an integer. However, because String types cannot be converted into integers, we get an error. An important thing to notice, however, is that if we implicitly declare the array, we don’t get an error by adding a String type object:

var = [10,5,6,89, ""]
//no error

What’s going on here is Swift is actually creating an NSArray as opposed to an Array. Those with Objective-C backgrounds will know what an NSArray is. This is why we always stress being as explicit as possible when writing Swift. You don’t want any unexpected results because Swift is inferring things. This also makes it difficult for someone else to read and understand. Be explicit whenever possible and you and your code will be much happier.

Accessing Array Objects

To access any of the objects inside an array, we do this by using subscript syntax, passing the index of the value we want to retrieve within square brackets after the name of the array:

array2[1]
//5

Be aware that indexing starts at 0. If we retrieve the object in the array with an index of 2, we are actually retrieving the third value in the array. Now let’s find out how many values are in the array by using the count property of the array:

array2.count
//4

If we try to retrieve a value with an index that exceeds the bounds of the array, you will receive an error.

array2[4]
//fatal error: Array index outside of range

Calling a negative index also gives you an error:

array2[-1]
//fatal error: Array index outside of range