switch case

SwiftPattern MatchingSentence 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

Was this helpful?