switch on other types
Swift โฉ Pattern Matching โฉ Sentence Patterns โฉ
// CGPoint
let point = CGPoint(x: 7, y: 0)
// switch on Tuple
switch (point.x, point.y) {
case (0, 0): print("On the origin!")
case (0, _): print("x=0: on Y-axis!")
case (_, 0): print("y=0: on X-axis!")
case let (x, y) where x == y:
print("On y = x")
default:
print("Quite a random point here.")
}
// Range<Int>
switch count {
case Int.min..<0: print("Negative count, really?")
case 0 : print("Nothing")
case 1 : print("One")
case 2..<5 : print("A few") // use `2..<5 ~= count` behind the scene
case 5..<10: print("Some")
default : print("Many")
}
//
switch char {
case
"A", "E", "I", "O", "U", "Y",
"a", "e", "i", "o", "u", "y": // ...
case
"A"..."Z",
"a"..."z": // ...
default: // ...
}
the following cases are equivalent:
// match on constant
case 2? == case .some(2)
๐ ๆฏ่ผ๏ผ switch case
let optionalN: Int? = 2
switch optionalN {
case 0? : print("Zero")
case 1? : print("One")
case 2? : print("Two")
case nil: print("None") // == case .none
default : print("Other")
}
๐พ ็จๅผ๏ผ replit
// ------------
// Mod
// ------------
/// equivalent classes
struct Mod {
let mod: Int // quotient
let rem: Int // remainder
}
extension Mod {
init(_ q: Int, _ r: Int){
mod = q
rem = r
}
}
// -----------------------------
// โญ custom operator ~=
// -----------------------------
/// usage: `Mod(3, 1) ~= 4`
func ~= (pattern: Mod, value: Int) -> Bool {
return value % pattern.mod == pattern.rem
}
// ------------
// Book
// ------------
struct Book {
let title : String
let author: String
let year : Int
}
// -----------------------------
// โญ custom operator ~=
// -----------------------------
/// usage: `1960 ..< 2020 ~= book`
func ~= (yearRange: Range<Int>, book: Book) -> Bool {
return yearRange ~= book.year
}
// ------------
// main
// ------------
// switch on `Int`
// โฑ 1. the `value` โญ
switch 5 {
// โญ custom pattern matching
// โญโโ 2 โโโฎ
case Mod(2, 0): print("2n") // 2. the `pattern` โญ
case Mod(3, 1): print("3n+1")
case Mod(3, 2): print("3n+2") // 3n+2
// โญ `default` is always required on custom types
default: print("other kind of number")
}
// Book
let book = Book(
title : "20,000 leagues under the sea",
author: "Jules Vernes",
year : 1870
)
// switch on `Book`
// โฑ 1. the `value` โญ
switch book {
// โญโโโโ 2 โโโโโฎ // 2. the `pattern` โญ
case 1800 ..< 1900: print("19th century") // 19th century
case 1900 ..< 2000: print("20th century")
default: print("Other century")
}
AliSoftware โฉ Pattern Matching
operator (~=) - pattern matching operator.
Last updated