switch case

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

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

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
        }
    }
}

Last updated