Helpme in for-loop in format (String,Int)

I am confused about a for-loop in Swift that I found in The Swift Programming Language (Swift 5.7). The code is as follows:

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
var largest = 0
for (_, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number

I’m specifically confused about the line 7, where the for-loop is used in the pattern "for (String, Int) in sth". When I replace _ with another text, that text never appears in the response. Can anyone tell me how to use this for-loop and what the difference is between this type of for-loop and other types?

>Solution :

When a Dictionary is treated as a Sequence, as in this case, its Element is (Key, Value). So the _ here is saying that the algorithm does not require the key. Only the value is bound, as numbers (an array of integers).

An equivalent way of writing this loop would be:

for numbers in interestingNumbers.values { ... }

This would avoid throwing away the key.

Leave a Reply