> For the complete documentation index, see [llms.txt](https://pakornpat.gitbook.io/ios-app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pakornpat.gitbook.io/ios-app/swift/branching.md).

# Branching

ในบางครั้งเราต้องการรันคำสั่งแตกต่างกันไปโดยขึ้นกับเงื่อนไขบางอย่าง ใน Swift จะมีวิธีการได้สองวิธี คือ ใช้ `if` หรือ `switch`&#x20;

`If` สามารถเขียนได้เหมือนภาษาอื่นทั่วไป

```swift
if isCar && isNew {
    print("new car")
} else if isCar {
    print("old car")
} else {
    print("not a car")
}
```

เราสามารถใช้ Ternary Conditional ได้แบบนี้  (เครื่องหมาย ? ต้องเว้น 1 เคาะ)

```swift
y = x > 4 ? 1 : 2
```

ส่วน `switch` สามารถเขียนได้แบบนี้

```swift
let personAge = 7
switch personAge {
   case 0..<1: print("baby")
   case 1..<3: print("toddler")
   case 3..<5: print("preschooler")
   case 5..<13: print("gradeschooler")
   case 13..<18: print("teen")
   default: print("adult")
}
```

{% hint style="info" %}
โดยปกติแต่ละเคสของ switch เมื่อรันเสร็จ จะหลุดออกจาก switch เลย นั่นคือ ไม่ fallthrough ถ้าต้องการให้รันเคสลำดับถัดไปด้วย ต้องใช้ keyword `fallthrough`&#x20;
{% endhint %}

เราสามารถใส่เงื่อนไขในแต่ละเคสเพิ่มได้

```swift
let temperature = 21.5
let humidity = 22.0

switch (temperature, humidity) {
   case let (t,h) where t > h: print("humidity lower")
   case let (t,h) where t < h: print("humidity higher")
   default: "humidity and temperature are the same"
}
```

สามารถใช้ tuple ได้ และสามารถนำค่าออกมาใช้ในเคสได้

```swift
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}
```

{% hint style="info" %}
ในกรณีที่เราเขียน `case` จนครบทุกเงื่อนไข เราไม่ต้องใส่ `default`&#x20;
{% endhint %}

`switch` ยังใช้ในการถอดค่า associate value จาก Enum

```swift
enum PaymentType {
    case cheque
    case creditCard(number:String)
}

let payment = PaymentType.creditCard(number: "1234567890123456")

switch payment {
case .cheque: print("cheque")
case .creditCard(let number): print("credit card number: " + number)
}
```
