switch case let ... where

Swift โŸฉ Pattern Matching โŸฉ Sentence Patterns โŸฉ

  • let: variable binding.

  • where: condition on bound variable.

๐Ÿ’พ ็จ‹ๅผ๏ผš replit

import Foundation            // for URL

// -------------
//     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 {
    
    /// media title
    var title: String {
        switch self {
        // 2: โญ switch case let 
        //    (pattern matching + data binding)
        // --------------------------------------------------------
        //  - labels can be omitted
        //  - `case let .book(x, y, z) == case .book(let x, let y, let z)`
        //  - `case let .book(x, _, _) == case .book(let x, _, _)
        case let .book   (t, _, _): return t
        case let .movie  (t, _, _): return t
        case let .website(t, _, _): return t
        }
    }
    
    /// media title too
    var title2: String {
        switch self {
        // 3: โญ switch case let 
        //    (pattern matching + binding multiple cases)
        // -----------------------------------------------
        case 
            .book   (let t, _, _), 
            .movie  (let t, _, _), 
            .website(let t, _, _): return t
        }
    }
    
    func isPublished(after year: Int) -> Bool {
        switch self {
        // 5: โญ switch case let ... where
        // -------------------------------
        //   (pattern matching + data binding + condition on binding)
        //  - Note:
        //    โ€ข  `case .a(let x), .b(let x) where x > 0` is NOT equivalent to
        //       `case .a(let x) where x > 0, .b(let x) where x > 0`
        //    โ€ข  `case let .a(x), .b(x) where x > 0` WON'T compile.
        //       "โ›”๏ธ error: `x` must be bound in every pattern"
        case
            // for demo of `where` clause only, not recommended
            .book(_, _, let y) where y > year, 
            .movie(_, _, let y) where y > year, 
            .website(_, _, let y) where y > year: 
                return true
            // recommended way
            // case let .book(_,_,y), .movie(_,_,y) ... : return y > year
            default: return false
        }
    }
}

Last updated