operator (~=)
⭐️ 注意:在自訂 ~= 運算時,一定要遵循 pattern ~= value
的模式。
func ~=<P, V>(pattern: P, value: V) -> Bool
Swift uses various overloads of the ~=
operator to do pattern matching, which also lets us define our own overloads ... 👉 Sundell
Ole 提及如何設計一個 generic operator:
func ~=<T>(pattern: (T) -> Bool, value: T) -> Bool {
return pattern(value)
}
Sundell 提及如何設計一個 generic pattern:
// Sundell 的做法等於是將 Ole 的做法包裝在一個 struct 裡面,
// 但兩者的精神是一樣的。
struct Pattern<Value> {
let match: (Value) -> Bool
}
func ~=<T>(pattern: Pattern<T>, value: T) -> Bool {
pattern.match(value)
}
💾 程式:replit
// -----------------------------
// ⭐ custom ~= operator
// -----------------------------
// matches a "boolean keypath into a type" (instance.booleanProperty)
// against an "instance of that type" (instance)
// ⭐ matching pattern: "pattern" ~= "value"
func ~=<T>(keypath: KeyPath<T, Bool>, instance: T) -> Bool {
// ⭐ \.isNumber ~= Character("3") returns Character("3").isNumber
return instance[keyPath: keypath]
}
// extension
extension Character {
func expressYourself() {
switch self {
// built-in ~=
case "<" : print("\(self) is an Element tag")
case "#" : print("\(self) is a Hash tag")
// ⭐ custom ~= applied here
case \.isNumber : print("\(self) is a Number")
case \.isNewline: print("\(self) is a NewLine")
default : print("\(self) is something else")
}
}
}
// ------------
// main
// ------------
let chars: [Character] = [
"<", "#", "8", "\n", "x"
]
chars.forEach { $0.expressYourself() }
// < is an Element tag
// # is a Hash tag
// 8 is a Number
//
// is a NewLine
// x is something else
💾 程式:replit
// ⭐ `str ~= person` returns `str == person.name`
func ~=(str: String, person: Person) -> Bool {
return str == person.name
}
// custom type
struct Person {
let name : String
}
extension Person {
func areYou(_ name: String) {
switch name {
// ⭐ custom ~= applied here
case self.name: print("Hey it's me!")
default : print("Not me")
}
}
}
let joe = Person(name: "Joe")
joe.areYou("Joe") // Hey it's me!
operator - all operators
generics - about generic functions/types.
CaseReflectable - custom protocol for enum case name & associated values.
switch on other types - switch on custom types.
~= operator in Swift ⭐️ (💈例二)
Last updated
Was this helpful?