Arrays In Swift Explained
If you’re working with many pieces of data it would be hard to manage them with simply constants and variables. In that case, Arrays can make our life easier. Do You Want to Learn How?
Arrays are one of three collection types available in the Swift programming to manage our data. They are extremely useful for storing ordered sets of data. In this guide, we are going to learn how to Create, Modify and Iterate over an Array. But first, let’s think of an array as a collection of data that is ordered by index. If that doesn’t tell you much, we can see exactly how official Swift programming language guide defines an array:
“An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions”
The Swift Programming Language
So Arrays are absolutely everywhere throughout programming, and it’s a core fundamental concept you absolutely need to know.
Creating an Array
Arrays are a list of values that are the same type. Plus we have a universal language to create an array in pretty much every programming language. It’s actually two square brackets, where we specify the type of array. Lastly, we call the initializer, with an open and close bracket to create an empty array. That’s how we create a simple array. The most important thing about
var nameOfTheArray = [Type of Array]()
Defining an Empty Array
If we want to have a collection of cars, instead of creating individual variables for each brand, we can use an array. While we declare an empty array it’s also important to utilize, since it doesn’t have any values.
var carBrands = [String]() var carParts = [Int]()
An empty array would contain no data at first and it can only store data of a certain type that you specify. So now
Array with a Default Value
We can even provide some default value when we first create the array, separated by a
var carBrands: [String] = ["BMW", "Mercedes-Benz", "Audi", "Volvo", "Ford"]
The following code tells our playground that this is an array of Strings with an initial set of values. Here we have an array of
Since Swift has type inference feature we don’t need to declare the date type again. So we can simply write:
var carBrands = ["BMW", "Mercedes-Benz", "Audi", "Volvo", "Ford"]
Note: When you’recreating an empty array, It is required to declare the type of array, because the compiler can’t infer anything. But if you have an array with some initial values then you can take
Adding Two Arrays Together
Another way to combine arrays is to add them together.
var numbers = [1, 2, 3] var newNumbers = [4, 5, 6] var combinedArray = numbers + newNumbers print(combinedArray)
The main difference between appending and combining two different arrays is that. In the first case we are actually changing the initial array, however
Accessing and Modifying an Array
An array stores a whole collection of variables in an ordered list. So we start our index at 0 going upwards until we reach the end of an array. The zero index means that is the very first element inside of our array, which is important to remember. The following concept will catch you out if you are a beginner quite a few times. So always remember that the first item in the array is index zero and it is at position zero not position one.
Accessing Elements in the Array
There are five spots or index for each item in our array. So if I wanted to access “BMW” I would write
var carBrands: [String] = ["BMW", "Mercedes-Benz", "Audi", "Volvo", "Ford"] carBrands[0] // Accessing first element carBrands.first // Accessing last element carBrands.last
Now if I change the index to 1 then I would get “Mercedes-Benz” instead. In addition, you can also access the first and the last element of the array just writing
But there has to be an easier way to get the first and less item in my list and the way to do that is by saying shopping list dot first okay shopping the stuff first that’s actually giving me a strength which we mean air over here so I say shopping list up first I’ll go ahead and get the first value in my array and that should be apples let’s give it a few seconds over here okay carBrands.first
And now if I say shopping list dot last I got the last value in my shopping list okay again those are two very nifty features that Swift tasks I’ll go into the count factor carBrands.last
Adding Value to Array
The thing that makes arrays really useful is that you can add and remove data from the collection. There are actually quite a few ways how to do that. The most simple one is to use a shorthand way of adding elements to your array, with the += sign. (addition assignment operator (+=)) In fact, you can even add two pieces of data at once separated by a comma with this technique.
// Adding single value carBrands += ["Ferrari"] // Adding multiple values carBrands += ["Lamborghini", "Porsche"]
Make sure that you don’t forget the plus sign because then you are basically creating a brand new array with two items while losing all the data in the previous array.
Moreover, we can use the append function to add new values to the array which is going to do exactly the same thing we did with the += sign.
// Appending single value carBrands.append("Porsche") // Appending another array var newCars = ["Lamborghini", "Porsche", "Maserati"] carBrands.append(contentsOf: newCars)
Now that’s just appending a single element let’s say you had another array of numbers you wanted to add to the end you can do that as well and there are two ways to do that. Let’s create another small array and appended it to our
If you try to append an integer in
Removing Elements
Now seeing this plus equals you might be tempted to use minus equals to remove items but that actually doesn’t work. Instead, you have to use the specific function that you can call to remove items. Swift also provides different function including removeAll() which is going to remove all the items in our array. But you can use remove(at: Int) to specify the index of the item you want to remove. If you know the index you can just do numbers dot remove at and then index and remove the element on a specific index.
// Remove the first item in the array // Returns the removed number at index 0 carBrands.remove(at: 0) // Remove all the values carBrands.removeAll()
So removing is quite simple and you can also do more convenient ones like remove first and you know remove last and that’ll pop off the first one and the last one respectively. When we remove an item everything after this item will be bumped across to fill the gap. So if we remove index two, index three would then become index two, index four become index three and so on everything will be bumped over to fill the gap.
// Remove the first element in the array carBrands.removeFirst() // Remove the last element the array carBrands.removeLast()
So can also remove the first person and we can remove the last element in the array.
Modifying Arrays
Swift gives you the option to not only access items in the array but also to modify them. You can actually change the item that is assigned at that index by typing carBrands square brackets put in the index you want to change and using the equal sign to assign something new into that spot.
carBrands[0] = “New Car”
So with this code, you are basically saying that whatever item is in the first position in my array go ahead and change it with a
We can also insert the new item at a specific index. It’s also worth noting that when we insert the new item in the array everything bumps over to make room for a new item. So if we insert an item at index 1 the item that was index one would become indexed 2, the item that was indexed 2 now becomes index 3 and so on to make room.
carBrands.insert(“Tesla”, at: 1)
Sorting and Reversing
Reverse and sort are actually quite easy and effective function which you can use in Swift. It will sort the
// Sorts the elements in place carBrands.sort() print(carBrands) // Sorts the elements is a new variable let sortedCars = carBrands.sorted() print(sortedCars)
The reason why you might be sued .sorted() function is that you might want you still have your original list. As you can see I still have my array in this original order but now I have a copy of that array that’s sorted. So you know there are certain circumstances where you might not want to lose the original order and this is when you would use sorted.
The opposite functions would be .reverse() and .reversed()
And one more cool thing that we can do with arrays we can take players and we can find out if it contains a certain object. For
// Returns true carBrands.contains(“BMW”) // Returns false carBrands.contains(“Cadillac”)
That’s some of the cool things that we can do with arrays and they’re pretty powerful we have so much control over this list.
Now so much of this is functions is only possible because the array which we defined is a mutable array. We declared
Count Function
If you want to figure out how many true values are inside the array or in other words how many items are in there you should look at the count. That’s going to return the number of items in your array, that is sometimes useful when you want to use a for loop with a range and you don’t know how many items are in the array. You can use this array dot count and get this number here but just keep in mind that although
carBrands.count
And that returns a number of entries that we have in our array.
You can use count function with a for loop to identify precisely the range of the loop by getting the minus one of the
Iterating Over an Array
Another thing that you can do with
var carBrands: [String] = ["BMW", "Mercedes-Benz", "Audi", "Volvo", "Ford"] for car in 0...4 { print("Cars In the Garage: " + carBrands[car]) }
So in the first iteration of this for loop counter is 0, since it’s a starting point in our array. So when the 0 gets passed to the array it will return the string “BMW” and the text will be printed in the console area. The following process continues until the for loop reaches the final element of the
var carBrands = ["BMW", "Mercedes-Benz", "Audi", "Volvo", "Ford"] for cars in carBrands { print("Cars In the Garage: " + cars) }
I want to show you another way to use a for loop with an array and that’s simply to say for cars in
So again this is just a basic introduction to for loops and rays and how they work together and now you can iterate through an array to get some values out of it all right so that’s a crash course in the basics of arrays again it’s a super fundamental concept you’re going to be using them all the time very wise of you to get to know them very well
Quick Recap
Arrays are very useful in any sort of programming language and you will be using them quite a lot. Along with some useful function which enables you to append, remove and modify the elements. But remember that it’s just the tip of the iceberg when it comes to arrays, again this was just the basics but it’s good enough to get you started.
In this tutorial you’ve learned:
- Arrays are used to store an
ordered list of values - Elements inside the array have to be the same type
- If the array is a variable type, you can always modify it
So we with the array we have so much control over the data and there’s no way we could ever do this with individual pieces of information. So that was our look at array post any questions down in the comments.