Programming in Swift: Fundamentals

Oct 19 2021 · Swift 5.5, iOS 15, Xcode 13

Part 2: Beginning Collections

14. Operating on Arrays

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 13. Arrays Next episode: 15. Challenge: Arrays

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 14. Operating on Arrays

Update Notes: The student materials have been reviewed and are updated as of October 2021.

Transcript: 14. Operating on Arrays

So you’ve learned how to create arrays, and how to append elements to them, using the append method and the += operator.

So you know how to get things into Arrays – but how do you get them back out?

You learned that tuples are zero-indexed; where the first element in a tuple is index 0, and the next element in a tuple is index 1, and so on. Arrays are also zero-indexed. So the first element in an array is at index 0, the next element at index 1, and so forth.

To get to an element at a specific index, you use what’s known as subscripting. Subscripting looks like this:

pastries[0]
  • You have the name of the array, then the index of the element you want in brackets.

You may wonder what happens if there’s nothing at an index that you try to subscript into. Let’s try it.

Your array has six elements in it, so let’s see what happens if you try to get something at index, say, 13:

You don’t have to worry about options with subscripting, but you do have to be careful!

pastries[13]

Ooh, that looks scary. But here’s the real error message that you need: “Index out of range”. The “range” of an array is the span of the indexes in your array; for a six-element array, the range is from zero to five.

Trying to get something from an index that doesn’t exist will give you nothing but errors.

Ranges can also refer to a subset of the elements in an array. Say you know for sure there are elements at indexes 1 through 3 of an array, and you want to grab that subset of elements and keep a reference to them in a new array.

To access a range of elements, simply specify a range inside the brackets to represent the indexes you want:

let firstThree = pastries[1...3]
  • There’s your cupcake, donut, and pie as expected!

  • This actually creates what’s known as an Array Slice, which is slightly different than an Array. It’s a stored reference to part of an array.

  • That means if you tried to get at index 0 of firstThree,

firstThree[0]

you’d get an error because the slice only has references to indexes 1 through 3.

To make a shiny, new zero-indexed array, you just need to use slightly different syntax

let firstThree = Array(pastries[1...3])

This takes the small slice of the original array, and casts it to a brand-new array, which then results in an array that starts at index zero, which you can see here:

firstThree[0]

I want to go back for a moment and revisit that append method. Arrays are a special kind of data type in Swift that have things called methods that you can use to perform certain operations on the array. You can also pull out some data about the array as well.

You used the append method to add a new element to an array, like this:

pastries.append("eclair")

If you wanted to remove every element from the array, there’s a method called “removeAll” to do that!

pastries.removeAll()
  • And now the Array is empty!

But you worked so hard to make all of those pastries! And we need elements in our Array to keep exploring, so I’m going to comment that out.

Yay - your pastries are back! What else can we do with them?

One piece of data an array has is a Boolean value named isEmpty, which tells you if the array is empty or not!

You can access this piece of data with the name of the array, followed by a dot, and then followed by the name of the piece of data you want to look at, in this case, isEmpty:

pastries.isEmpty
  • We can see that’s false in the sidebar over here.

You can also use the count property to find out how many pastries you have:

pastries.count

You can also find out what the first element in the array is with the first property.

pastries.first
  • If you Option-click on first you’ll see that it’s actually optional.

If you think about that for a moment, it makes sense. You know we can have an empty array. If there’s nothing in the array, it can’t have a first element.

Since this is an optional, what would be good practice here? Right - you want to safely unwrap this value. This is a good opportunity to use optional binding, like so:

if let first = pastries.first {
  print(first)
}
  • There’s your cookie in the debug console!

Another handy thing you can do is check to see if an array contains a specific value. For example, do we have a donut?

pastries.contains("donut")

We do! What about lasagna?

pastries.contains("lasagna")

We do NOT! That’s good. Unless it was chocolate lasagna… that would be ok.

We showed you two ways to append values to an array, but that just adds elements to the end. What if you want to insert a value somewhere in the middle of the array, at a specific index?

There’s a method for that, too: it’s called “insert”, or insert at. You simply call “insert” and then pass in the value you want to add, and the index you want to put it at, using the word “at”:

pastries.insert("tart", at: 0)
  • Now tart is the first element in the array of pastries!

If you don’t want something in your array any longer, you can also remove specific elements.

You can remove something at a specific index, with remove(at:)

let removedTwo = pastries.remove(at: 2)

And you can also remove the first or last element. Those both have special methods:

let removedLast = pastries.removeLast()

When you use these methods, they return the removed elements, in case you want to look at what you’ve removed:

removedTwo
removedLast
pastries
  • You can see in the results on the right that “removedTwo” now holds our cupcake, “removedLast” has our brownie, and the pastries array has neither!

So you can add and remove elements. But can you change them?

Yes, you absolutely can change the contents of an array! You can use subscripting to change the element at a specific index, or use a range to change multiple elements at once.

pastries[0...1] = ["brownie", "fritter", "tart"]
pastries

That’s a neat trick! You replaced two elements, at indexes 0 and 1, with three elements, a brownie, fritter, and tart.

  • Notice that this didn’t sneak in and replace something outside of the range of indexes specified.

  • The donut that was at index 2 is still there, it’s just at index 3 now! You don’t have to worry about shuffling things along in the array yourself; Swift takes care of that for you.

Let’s try swapping the position of some pastry. There’s a long tedious way you may have figured out. You could remove an element, store the result, and then insert it again.

But there’s a handy swapAt method on arrays that you should should instead!

pastries.swapAt(1, 2)
  • That takes two indexes, and then just swaps their values. So tart and fritter are now switched around.

That was a lot to take in!

I recommend keeping this playground around as a reference, but you should also look into the documentation of Arrays, yourself, to see what other properties and methods are available to you!

Now, it’s time for an array of mini-challenges about arrays!