Arrays in Swift 3

Arrays are data structures within programming and can be used to store a collection of elements. Arrays in Swift 3 are no different, however the syntax will vary between programming languages. Here we cover the basics of creating arrays, and adding and removing data from them.

To create an array, for example, an array to hold strings, declare a variable and assign it a pair of parentheses.

var a = [String]()

This is an empty array. The above also works for other types and not just strings. For example.

var b = [AnyObject]()

The above can store any object, whereas the below…

var c = [Double]()

…would create an array of doubles.

You can declare an array of existing data.

var animals = ["cat", "dog", "bird"]

Notice here that Swift likes to use double quotes rather than single quotes when declaring arrays.

You can then access each of these elements by specifying the index of the element. In programming, array indexes start from 0.

animals[0] // cat
animals[1] // dog
animals[2] // bird

Sometimes you may not know the number of elements within an array. You can found out the count using count.

animals.count // 3

You can use either insert or append to add an element to an array. If you use insert, you an specify which position to add the element.

animals.insert("mouse", at: 0)

The above example will add mouse at the start of the array, so the array list will now look like this.

["mouse", "cat", "dog", "bird"]

Using append, you can append a new element onto the end of the array.

animals.append("snake") 
// ["mouse", "cat", "dog", "bird", "snake"]

To remove an element from an array, use remove. You can then specify the index position of the element to remove. For example, to remove the element in position 1.

animals.remove(at: 1)
// ["mouse", "dog", "bird", "snake"]

Note: This article is based on Swift version 3.