Fogmeister Fogmeister - 11 months ago 56
Swift Question

~= operator in Swift

I recently downloaded the Advanced NSOperations sample app from Apple and found this code...

// Operators to use in the switch statement.
private func ~=(lhs: (String, Int, String?), rhs: (String, Int, String?)) -> Bool {
return lhs.0 ~= rhs.0 && lhs.1 ~= rhs.1 && lhs.2 == rhs.2

private func ~=(lhs: (String, OperationErrorCode, String), rhs: (String, Int, String?)) -> Bool {
return lhs.0 ~= rhs.0 && lhs.1.rawValue ~= rhs.1 && lhs.2 == rhs.2

It seems to use the
operator against
but I've never seen it before.

What is it?


It is an operator used for pattern matching inside the switch statement.

You can take a look here to know how you can use and leverage it providing your own implementation:

Here is a simple example of defining a custom one and using it:

struct Person {
    let name : String

// Function that should return true if value matches against pattern
func ~=(pattern: String, value: Person) -> Bool {
    return == pattern

let p = Person(name: "Alessandro")

switch p {
// This will call our custom ~= implementation, all done through type inference
case "Alessandro":
    print("Hey it's me!")
    print("Not me")

// Output: "Hey it's me!"