Iterating through an array

It’s getting late and the players decide to stop for the night and continue tomorrow; in the meantime, you’ll keep their scores in a separate array. You’ll see a better approach for this in the chapter on dictionaries, but for now you’ll continue using arrays:

let scores = [2, 2, 8, 6, 1, 2, 1]

Before the players leave, you want to print the names of those still in the game. You can do this using the for-in loop you read about in Chapter 5, “Advanced Control Flow”:

for player in players { print(player)

}

// > Anna

// > Brian

// > Craig

// > Dan

// > Donna

// > Eli

// > Franklin

This code goes over all the elements of players, from index 0 up to players.count

  • 1 and prints their values. In the first iteration, player is equal to the first element of the array; in the second iteration, it’s equal to the second element of the array; and so on until the loop has printed all the items in the array.

If you also need the index of each element, you can iterate over the return value of

the array’s enumerated() method, which returns tuples with the index and value of each element in the array.

for (index, player) in players.enumerated() { print("(index + 1). (player)")

}

// > 1. Anna

// > 2. Brian

// > 3. Craig

// > 4. Dan

// > 5. Donna

// > 6. Eli

// > 7. Franklin

Now you can use the technique you’ve just learned to write a function that takes an array of integers as its input and returns the sum of its elements:

func sumOfAllItems(in array: [Int]) -> Int { var sum = 0

for number in array { sum += number

}

return sum

}

You could use this function to calculate the sum of the players’ scores:

print(sumOfAllItems(in: scores))

// > 22

Mini-exercise

Write a for-in loop that prints the players’ names and scores.

results matching ""

    No results matching ""