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

# switch

🚧 施工中

[Swift](/ios/swift.md) ⟩ [flow control](/ios/swift/flow.md) ⟩ [branch](/ios/swift/flow/branch.md) ⟩ switch

{% hint style="danger" %} <mark style="color:yellow;">unlabeled</mark> <mark style="color:yellow;"></mark><mark style="color:yellow;">**'**</mark>[`break`](/ios/swift/flow/transfer/break.md)<mark style="color:yellow;">**'**</mark> is <mark style="color:red;">only</mark> <mark style="color:yellow;">allowed</mark> <mark style="color:yellow;">inside</mark> a [loop](/ios/swift/flow/loop.md) or <mark style="color:purple;">`switch`</mark>. \
( 👉 see： [for...in vs. forEach](/ios/swift/flow/loop/for...in-vs.-foreach.md) )
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
{% tabs %}
{% tab title="on Optional" %}

```swift
let value: Int? = 42

// switch on Optional
switch value {
    case .some(let n): print("有值：\(n)")
    case .none: print("無值")
}

// switch on Optional
switch value {

    // ⭐️ `case let n?` 相當於 `case .some(let n)`
    case let n?: print("有值：\(n)") 
    
    // ⭐️ where clause
    case let n? where n > 40: print("值大於 40：\(n)")
       
    // ⭐️ `case nil` 相當於 `case .none`
    case nil: print("無值")
    
    // ⭐️ 判斷是否為某特定值時，直接寫就可以
    case 42: print("值是 42")
}

// switch on tuple of optionals
switch (optionalA, optionalB){
    case (.some, nil):     // ⭐️ 不想綁定變數時：用 `.some`
    case (nil, .some):     // ...
    case (let x?, let y?): // ⭐️ 綁定變數時：用 `let x?`
    case (nil, nil):       //
}
```

{% endtab %}

{% tab title="on Tuple" %}

```swift
// switch on tuple of optionals
switch (optionalA, optionalB){
    case (.some, nil):     // ⭐️ 不想綁定變數時：用 `.some`
    case (nil, .some):     // ...
    case (let x?, let y?): // ⭐️ 綁定變數時：用 `let x?`
    case (nil, nil):       //
}
```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="👥 相關" %}

* [Optional](/ios/swift/type/category/basic/optional.md)
  {% endtab %}

{% tab title="📘 手冊" %}

* [ ] Swift ⟩&#x20;
  * [Conditional Statements](https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID127) ⟩ switch
  * [Patterns](https://docs.swift.org/swift-book/ReferenceManual/Patterns.html) ⟩ [Optional Pattern](https://docs.swift.org/swift-book/ReferenceManual/Patterns.html#ID520)
    {% endtab %}

{% tab title="📗 參考 " %}

* [ ] [Exercism](https://exercism.org/tracks/swift/exercises/pizza-slices)
  {% endtab %}
  {% endtabs %}
