operator (~=)

SwiftPatterns

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)
}

Last updated

Was this helpful?