Home > OS >  I am not too sure what is going on in this block of swift code. Anyone know how to explain this?
I am not too sure what is going on in this block of swift code. Anyone know how to explain this?

Time:04-07

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

How does this print 25? I am rather new to coding and am still learning so I am trying to get a good handle on how everything works.Could someone please explain this to me?enter code here

CodePudding user response:

for loops take along time to read and understand because their possibilities are infinite—you can vary results wildly with subtle changes. Most of the time, when people use a loop, they should reach for premade named tools, which are built on loops. It's a never-ending process, learning those, but it's axe sharpening, allowing you to remove bugs and communicate more effectively.

The name for this code is max.

for number in numbers {
  if number > largest {
     largest = number
  }
}

The name for this code is flatMap.

for (_, numbers) in interestingNumbers {
 for number in numbers {

Your code is reinventing this wheel:

interestingNumbers.flatMap(\.value).max()

…meaning, "the maximum value found in all of interestingNumbers's values".

CodePudding user response:

The code you posted is a loop inside another loop (also known as nested loops.)

The outer loop loops through the key/value pairs in a dictionary.

The inner loop loops through the array of integers from the value of each dictionary.

See if you can reason out what the inner code does. It's only a few lines. As Larme suggested, maybe you sould add print statements inside the outer inner loops to log what is happening at each step:

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 (key, numbers) in interestingNumbers {
 print("For key \(key) numbers: \(numbers)")
 for number in numbers {
    print("number: \(number)")
    if number > largest {
        print("Replacing previous largest value of \(largest) with \(number)")
        largest = number
    }
  }
}

Then run the program and examine the output carefully.

  • Related