# Loops

การวนลูปคือการรันคำสั่งในบล๊อกของลูปซ้ำหลาย ๆ ครั้งตามจำนวนหรือเงื่อนไขที่กำหนด เช่น วนพิมพ์ค่าตั้งแต่ `0` ถึง `9`&#x20;

โดยทั่วไปหลาย ๆ ภาษาจะสามารถเขียนลูปได้แบบนี้

```c
for(int i = 0; i < 10; i++)
   printf("i=%d\n", i);
```

แต่ใน Swift จะไม่สามารถเขียนแบบนี้ได้ แต่ให้เขียนเป็นลูป `for in` แทน เราสามารถใช้ range มาช่วยได้แบบนี้

```swift
for i in 0..<10 {
    print(i)
}
```

{% hint style="info" %}
ในบางครั้งเราต้องการเพิ่มค่า `i` ทีละ 2 แบบนี้

```swift
for(int i = 0; i < 10; i += 2)
```

Swift จึงเตรียมฟังก์ชั่น `stride(from:to:by:)` ให้แบบนี้

```swift
for index in stride(from: 0, to: 10, by: 2)
// index is 0, 2, 4, 6, 8
```

หรือ `stride(from:through:by:)` ให้แบบนี้

```swift
for index in stride(from: 0, through: 10, by: 2)
// index is 0, 2, 4, 6, 8, 10
```

{% endhint %}

เราสามารถวนแบบ `for each` ได้ด้วยการเขียน `for in` แบบเดียวกัน เช่น

```swift
var shoppingList = ["catfish", "water", "tulips"]
for item in shoppingList {
    print(item)
}
```

ในกรณีที่เราต้องการ `index` ของ item ที่วนลูปอยู่ด้วย ให้เราใช้ tuple มารับผลลัพธ์จาก `enumerated()` อีกทีนึง

```swift
for (index, item) in shoppingList.enumerated() {
    print("The item at index \(index) is \(item)")
}
```

เราสามารถใส่เงื่อนไขการเข้าทำงานในลูปได้ด้วย `where` ทำให้ลดการใส่ `if` ในลูปของเราได้ด้วย

```swift
for item in shoppingList where item.starts(with: "c") {
    print(item)
}
```

ทั้งยังสามารถใช้ `break` ในการหยุดและออกจากลูปทันที หรือใช้ `continue` ในการข้ามไปยังลูปครั้งถัดไปได้เหมือนภาษาอื่น

นอกจาก `for` ยังมี `while` กับ `repeat while` ด้วย

ในกรณีที่ต้องการเช็คเงื่อนไขก่อนให้ใช้ `while` &#x20;

```swift
while shoppingList.count > 0 {
    print(shoppingList.remove(at: 0))
}
```

ในกรณีที่ต้องการทำคำสั่งในบล๊อกก่อนหนึ่งรอบแล้วค่อยเช็คเงื่อนไขใช้ `repeat while`&#x20;

```swift
repeat {
    print(shoppingList.remove(at: 0))
} while shoppingList.count > 0
```


---

# 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://pakornpat.gitbook.io/ios-app/v2/swift/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.
