# switch

[Swift](https://lochiwei.gitbook.io/ios/swift) ⟩ [flow control](https://lochiwei.gitbook.io/ios/swift/flow) ⟩ [branch](https://lochiwei.gitbook.io/ios/swift/flow/branch) ⟩ switch

{% hint style="danger" %} <mark style="color:yellow;">unlabeled</mark> <mark style="color:yellow;"></mark><mark style="color:yellow;">**'**</mark>[`break`](https://lochiwei.gitbook.io/ios/swift/flow/transfer/break)<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](https://lochiwei.gitbook.io/ios/swift/flow/loop "mention") or <mark style="color:purple;">`switch`</mark>. \
( 👉 see： [for...in-vs.-foreach](https://lochiwei.gitbook.io/ios/swift/flow/loop/for...in-vs.-foreach "mention") )
{% 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](https://lochiwei.gitbook.io/ios/swift/type/category/basic/optional "mention")
  {% 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 %}
