Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
        }
    }
}
print(largest)

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading