2.1. Arrays

An array is a data structure that can store a collection of values of the same data type. An array is an ordered data structure, which means the elements are stored in a specific order, and an element stays at the same position/index until changed.

In Swift, we create arrays with [DataType].

For example, the following code creates an empty array of strings that holds the name of car brands:

var carMakes = [String]()

Or, we can initialize an array with predefined values using an array literal, which is a list of values enclosed in square brackets. For example, the following code creates an array of strings to hold two initial car manufacturers, Toyota and Honda:

var carMakesSecond = ["Toyota", "Honda"]

Please note, in the above example, Swift automatically defines the variable type of carMakesSecond to an array of strings.

Adding a new element to an existing array:

To add a new element in an array, we use append() function. For example, to add a new car brand in the carMakes array, we can write the following:

carMakes.append("Mazda")

// Print the current elements of the array...
print(carMakes)

If you run the code, it will print the following outputs:

["Mazda"]

Let's add a couple more brands:

carMakes.append("Toyota")
carMakes.append("Honda")

// Print the current elements of the array...
print("After appending: \(carMakes)")

The above code outputs:

Size of an existing array:

We can get the size of an array by accessing the count attribute. carMakes.count is the size of carMakes. For example,

prints:

Accessing an element from a particular position:

We can access an element of an array by it's index/position in the array. The indices start at 0. So, the first element resides at position 0, the second element resides at position 1, and so on. For example, let's look at the following code:

It will print the following output:

Removing an element from an existing array:

We can remove an element from an element by calling remove(at: index) function. For example:

This code outputs:

So far, we have learned the basics about Swift arrays (declaring and initializing an array, adding and removing elements). We will explore more functionalities cumulatively further down the road.

Last updated

Was this helpful?