operator (~=)
⭐️ 注意:在自訂 ~= 運算時,一定要遵循 pattern ~= value 的模式。
func ~=<P, V>(pattern: P, value: V) -> Bool💾 程式: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?