Skip to content

Instantly share code, notes, and snippets.

@dmcrodrigues
Last active March 3, 2016 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmcrodrigues/c6234080c99121fc40b1 to your computer and use it in GitHub Desktop.
Save dmcrodrigues/c6234080c99121fc40b1 to your computer and use it in GitHub Desktop.
Expression pattern operator ~=
import UIKit
class A {
var value: Int
init(value: Int) {
self.value = value
}
}
extension A: Comparable {}
func == (lhs: A, rhs: A) -> Bool {
return lhs.value == rhs.value
}
func < (lhs: A, rhs: A) -> Bool {
return lhs.value <= rhs.value
}
// MARK: Pattern matching
func ~=(pattern: [A], value: A) -> Bool {
return pattern.contains(value)
}
func ~=(pattern: A, value: [A]) -> Bool {
return value ~= pattern
}
// Example
let array1 = [A(value: 1), A(value: 5)]
let array2 = [A(value: 3), A(value: 4)]
let a = A(value: 1)
switch a {
case array1: print("Matched on array1")
case array2: print("Matched on array2")
default: print("Not matched")
}
switch array1 {
case a: print("`a` matched")
default: print("Not matched")
}
// Output:
// "Matched on array1"
// "`a` matched"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment