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 variablefor 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
for i in1...12 {print("5 x \(i) is \(5* i)")}/*print:5 x 1 is 55 x 2 is 105 x 3 is 155 x 4 is 205 x 5 is 255 x 6 is 305 x 7 is 355 x 8 is 405 x 9 is 455 x 10 is 505 x 11 is 555 x 12 is 60*/
Nested Loops
In the below example, you may see that we used "up to" operator "..<" in order to limit the loop dynamically.
for i in1..<4 {print("The \(i) times table:")for j in1...2 {print(" \(j) x \(i) is \(j * i)") }print()}/*print:The 1 times table: 1 x 1 is 1 2 x 1 is 2The 2 times table: 1 x 2 is 2 2 x 2 is 4The 3 times table: 1 x 3 is 3 2 x 3 is 6*/
Loop without variable
In some cases you may not need a variable. So you can define it as "_"
var lyric ="Haters gonna"for_in1...5 { // her is variable is "_' lyric +=" hate"}print(lyric)
Examples
var numbers = [1, 2, 3, 4, 5, 6]for number in numbers {if number %2==0 {print(number) }}/*print:246*/
for i in1...8 {if i <3 {print("\(i) is a small number") }}/*print:1 is a small number2 is a small number*/
Be aware of where you put the "Break". If you put it in the wrong place it will stop earlier.
var password ="1"whiletrue { password +="1"if password =="11111" {print("That's a terrible password.")break// exact point }}// print: That's a terrible password.// --var password ="1"whiletrue { password +="1"if password =="11111" {print("That's a terrible password.") }break// wrong place}// print: ""
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
for i in1...100 {if i %3!=0 { if i %5!=0 { print(i)} }if i %3==0 { print("\(i) = Fizz") }if i %5==0 { print("\(i) = Buzz") }if i %3==0 { if i %5==0 { print("\(i) = FizzBuzz") } }}/*print:123 = Fizz45 = Buzz6 = Fizz789 = Fizz10 = Buzz1112 = Fizz131415 = Fizz15 = Buzz15 = FizzBuzz...*//