Loops
#loop #forloop #whileloop #forwhileloop #conditionals
Overview
Since you cannot change a number in "let", all the numbers should use "var"
For vs While
For: Finite (you give a range from the beginning)
While: Unpredictable (Until meets the target)
For Loop
example 1
let platforms = ["iOS", "macOS", "tvOS", "watchOS"]
// array
// os: loop variable
for os in platforms {
print("Swift works great on \(os).")
}
// loop iteration
/*
print:
Swift works great on iOS.
Swift works great on macOS.
Swift works great on tvOS.
Swift works great on watchOS.
*/Loop over a fixed range of numbers
Nested Loops
In the below example, you may see that we used "up to" operator "..<" in order to limit the loop dynamically.
Loop without variable
In some cases you may not need a variable. So you can define it as "_"
Examples
While Loop
Skipping Loop items
Breaking in a point
Be aware of where you put the "Break". If you put it in the wrong place it will stop earlier.
Continue vs Break
Continue: As long as the result meets the criteria Continue
Break: Stop at a certain point
When we use continue we’re saying “I’m done with the current run of this loop” – Swift will skip the rest of the loop body, and go to the next item in the loop. But when we say break we’re saying “I’m done with this loop altogether, so get out completely.” That means Swift will skip the remainder of the body loop, but also skip any other loop items that were still to come. (HWS)
FizzBuzz
Sources
Videos
Articles / Documents
Last updated
Was this helpful?