# Loops

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

```swift
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

```swift
for i in 1...12 {
    print("5 x \(i) is \(5 * i)")
}

/*
print:

5 x 1 is 5
5 x 2 is 10
5 x 3 is 15
5 x 4 is 20
5 x 5 is 25
5 x 6 is 30
5 x 7 is 35
5 x 8 is 40
5 x 9 is 45
5 x 10 is 50
5 x 11 is 55
5 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.

```swift
for i in 1..<4 {
    print("The \(i) times table:")

    for j in 1...2 {
        print("  \(j) x \(i) is \(j * i)")
    }

    print()
}

/*
print:

The 1 times table:
  1 x 1 is 1
  2 x 1 is 2

The 2 times table:
  1 x 2 is 2
  2 x 2 is 4

The 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 "\_"

```swift
var lyric = "Haters gonna"

for _ in 1...5 { // her is variable is "_'
    lyric += " hate"
}

print(lyric)
```

### Examples

```swift
var numbers = [1, 2, 3, 4, 5, 6]
for number in numbers {
    if number % 2 == 0 {
        print(number)
    }
}

/*
print:

2
4
6

*/
```

```swift
for i in 1...8 {
    if i < 3 {
        print("\(i) is a small number")
    }
}

/*
print:

1 is a small number
2 is a small number

*/
```

## While Loop

### Skipping Loop items

```swift
let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"]

for filename in filenames {
    if filename.hasSuffix(".jpg") == true {
        continue
    }

    print("Found picture: \(filename)")
}

/*
print:

Found picture: work.txt
Found picture: logo.psd

*/


// --------------

let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"]

for filename in filenames {
    if filename.hasSuffix(".jpg") == false {
        continue
    }

    print("Found picture: \(filename)")
}

/*
print:

Found picture: me.jpg
Found picture: sophie.jpg

*/
```

### Breaking in a point

```swift
let number1 = 10
let number2 = 14
var multiples = [Int]()

for i in 1...100_000 {
    if i.isMultiple(of: number1) && i.isMultiple(of: number2) {
        multiples.append(i)

        if multiples.count == 10 {
            break
        }
    }
}

print(multiples)

// print: [70, 140, 210, 280, 350, 420, 490, 560, 630, 700]
```

Be aware of where you put the "Break". If you put it in the wrong place it will stop earlier.

```swift
var password = "1"
while true {
    password += "1"
    if password == "11111" {
        print("That's a terrible password.")
        break // exact point
    }
}
// print: That's a terrible password.

// --

var password = "1"
while true {
    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](https://www.hackingwithswift.com/quick-start/understanding-swift/when-to-use-break-and-when-to-use-continue))

## FizzBuzz

```swift
for i in 1...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:

1
2
3 = Fizz
4
5 = Buzz
6 = Fizz
7
8
9 = Fizz
10 = Buzz
11
12 = Fizz
13
14
15 = Fizz
15 = Buzz
15 = FizzBuzz
...

*//
```

## Sources

### Videos

### Articles / Documents

* <https://www.hackingwithswift.com/100/swiftui/6>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://swift.sedatonat.dev/codes/loops.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
