# switch case



[Swift](../..) ⟩ [Pattern Matching](..) ⟩ [Sentence Patterns]() ⟩

{% hint style="success" %}
* <mark style="color:red;">**case**</mark>: [pattern matching](..).
{% endhint %}

{% tabs %}
{% tab title="💈範例" %}
💾 程式： [replit](https://replit.com/@pegasusroe/Pattern-Matching-switch-case#Media.swift)

```swift
import Foundation            // for URL

// -----------------
//     Direction
// -----------------

enum Direction {
    case north, south, east, west
}

extension Direction: CustomStringConvertible {
    var description: String {
        switch self {
            // 1: ⭐ switch case 
            //    (pattern matching on constants)
            // ------------------------------------
            case .north: return "⬆️"
            case .south: return "⬇️"
            case .east : return "➡️"
            case .west : return "⬅️"
        }
    }
}

// -------------
//     Media
// -------------

/// enum with associated values
enum Media {
    case book(title: String, author: String, year: Int)
    case movie(title: String, director: String, year: Int)
    case website(title: String, url: URL, year: Int)
}

extension Media {
    /// usage: `media.is(from: author)`
    func `is`(from author: String) -> Bool {
        switch self {
            // 4: ⭐ switch case 
            //    (pattern-match on variables/constants)
            // -------------------------------------------
            case .book (_, author  : author, _): return true
            case .movie(_, director: author, _): return true
            default: return false
        }
    }
}
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] [Part 1: switch, enums & where clauses](https://alisoftware.github.io/swift/pattern-matching/2016/03/27/pattern-matching-1/) ⭐️
{% endtab %}
{% endtabs %}
