iOS Swift Collections and Control Flow Control Flow With Loops While and Repeat While

NIKOLA RUSEV
NIKOLA RUSEV
5,293 Points

1 task while loop

while counter < numbers.count { sum += numbers[counter] counter += 1 }

what is wrong with this code?

3 Answers

Moritz Lang
Moritz Lang
25,909 Points

Hey Nikola, I would recommend to write your loops in multiple lines, because it's easier to read and to understand.

while counter < numbers.count { 
    sum += numbers[counter]
    counter += 1
}

Other than that I don't understand what's wrong with your code. It would be usefull if you could provide the exact error.


Personally I would also use a for-loop for this kind of operation, because there is not really a need for the counter variable. This could look like this:

for number in numbers {
    sum += number
}
Moritz Lang
Moritz Lang
25,909 Points

Glad you figured it out :) But you only need the ";" if you want to write the condition all in one line (which is not so good style). I would preffer the more readable way and put it into multiple lines.

The ";" is just to separate two expressions from one another. In Swift this could also be done by a line break. Thats why you almost never need the ";" in Swift. But if you put two expressions (sum += numbers[counter]; counter += 1) in one line you have to separate them manually, because the compiler thinks that they are one expression, but could not evaluate it.

NIKOLA RUSEV
NIKOLA RUSEV
5,293 Points

the task ask to use while loop, but i solve problem. i didnt put ";" the code should look like while counter < numbers.count { sum += numbers[counter]; counter += 1}

thank you anyway