Start learning free

LESSON 276 OF 678 · TUPLES, SORTING & BUILT-INS

enumerated and zip in Swift

Lesson

TL ; DR:

enumerated() gives each item with a count. zip walks two arrays side by side.


let fruits = ["apple", "kiwi", "plum"]
let prices = [3, 1, 2]

for (i, fruit) in fruits.enumerated() {
    print("\(i + 1). \(fruit)")    // 1. apple, then 2. kiwi, then 3. plum
}

for (fruit, price) in zip(fruits, prices) {
    print("\(fruit) \(price)")     // apple 3, then kiwi 1, then plum 2
}


Full lesson:

You have looped with for i in 0..<meals.count. Then meals[i] gave the item. Swift has a shorter way to get both.

enumerated() gives each item together with a count. The loop unpacks the tuple into two names, as let (name, age) = pet does.

for (i, meal) in meals.enumerated() {
    print("\(i) \(meal)")
}

The count comes first. It starts at 0, so print i + 1 for a numbered list.

zip(a, b) walks two arrays side by side. It pairs the first item of a with the first item of b. Then it pairs the second items, and so on. Each pair is a tuple.

for (fruit, price) in zip(fruits, prices) {
    print("\(fruit) costs \(price)")
}

zip is a function, not a method of the array. Write zip(fruits, prices), not fruits.zip(prices).

zip stops at the end of the shorter array. The extra items are skipped, with no error.

The two work together. zip(fruits, prices).enumerated() gives a count and a pair each time. The names nest the same way.

for (i, (fruit, price)) in zip(fruits, prices).enumerated() {
    print("\(i + 1). \(fruit) costs \(price)")
}

Your task

A quiz show keeps its players in the array players. Their points are in scores, in the same order.

First, print the players as a numbered list from 1, like 1. Ana. Use enumerated().

Then print each player with their points, like Ana has 12 points. Use zip.

Expected output:

1. Ana
2. Ben
3. Cleo
Ana has 12 points
Ben has 9 points
Cleo has 15 points
STEP 1 OF 4
    Ctrl + Enter to check