switch case
Swift โฉ Pattern Matching โฉ Sentence Patterns โฉ
case: pattern matching.
๐พ ็จๅผ๏ผ 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