Programming in Swift: Fundamentals

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

Part 3: Control Flow

23. Challenge: Iterating Collections

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: 22. Iterating Collections Next episode: 24. Nested Loops & Early Exit

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: 23. Challenge: Iterating Collections

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

Transcript: 23. Challenge: Iterating Collections

It’s time for your next challenge! You can find the challenge in the “07 - Challenge - Iterating Collections” page of the playground you’ve been using, or you can download a new one from the resources for this video. Open it up, and try solving the challenge questions on your own, then keep watching to compare your work to mine. Good luck!

Create a loop that iterates over each element of the array, and uses an if statement inside the loop to print out the pastries that start with the letter “c”. Let me set up my for loop to iterate over all items in the array:

for pastry in pastries {

Then, I need an if block, and I can use this condition here - if the element of pastry at pastry.startIndex, which is the first character in the string, is equal to c:

if pastry[pastry.startIndex] == "c" {

…then I want to print out the pastry name:

print(pastry)

And the console shows me that C is for cookie, cupcake, and cruller. Good work!

Now, writing tidy and compact code is the mark of a good developer, so let’s try and tighten this code up. I’ll begin by creating the for loop:

for pastry in pastries

…and then I’ll add a where clause - where the first character of the pastry name is equal to c:

for pastry in pastries where pastry[pastry.startIndex] == "c" {

So that filters the range of elements in the array to just the ones that begin with c. That means all I have to do is now print out the names of the pastries that I am iterating over:

print(pastry)

And that’s it! There’s the same list of pastries in the console.

You can see how your code is a little easier to read now, with fewer lines. Head on in to the next video, where I’ll go over nesting loops and how to exit early! I mean, an early exit from loops, not an early exit from the video — we still have a few videos left to go! I’ll see you there.