Last active
March 3, 2016 12:39
-
-
Save dmcrodrigues/c6234080c99121fc40b1 to your computer and use it in GitHub Desktop.
Expression pattern operator ~=
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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