What is an Array?
An Array is a type of variable that can hold a list of values, which we can access using an index.
Imagine we need to store a user's shopping list. We could keep the items in an Array. An Array is represented by the type of variables it contains within square brackets. We can give it an initial value by placing all the values between two square brackets and separating them with commas.
var items: [String] = ["Potatoes", "Tomato", "Cucumber"]
Accepted Types in an Array
Until we explore variable types in more detail, we can say that an Array must be homogeneous, meaning that if we have an Array of integers, or [Int], we cannot insert any other type of variable that isn't an Int.
Accessing Items
To access one of these values, you can do so by indicating its position, starting from 0. For example, if we want to access "Tomato", we would use index 1.
print(items[0]) // Console shows: Potatoes
print(items[1]) // Console shows: Tomato
print(items[2]) // Console shows: Cucumber
items
array.
Adding a New Item to an Array
Continuing with the same example, let's imagine the user adds a new item. In that case, we would want to insert it into the Array. Since Arrays are an ordered list, the new item can be inserted at the beginning, the end, or in any intermediate position.
Here are the two most common options:
// Adds "Onion" at the last position, resulting in ["Potatoes", "Tomato", "Cucumber", "Onion"]
items.append("Onion")
// Adds "Fruit" at the first position, resulting in ["Fruit", "Potatoes", "Tomato", "Cucumber", "Onion"]
items.insert("Fruit", at: 0)
Trying to insert an item into a non-existent position would also cause a crash.
Removing an Item
There are several methods to remove items from an Array, which we will cover later. Here's an example of how to remove an item by its index.
// ["Fruit", "Potatoes", "Tomato", "Cucumber", "Onion"]
items.remove(at: 1) // Removes the item "Potatoes"
Be the first to comment