2

I wonder which type of value can be compared in switch statement. The official document said:

Cases can match many different patterns, including interval matches, tuples, and casts to a specific type

Is there anything else? Can I compare class type in switch statement?

Suppose I hava a class A:

class A {
}
func == (lhs: A, rhs: A) -> Bool { return true }

Then I can check if two objects of class A are equal. But I still can't do like this:

var a1 = A(); var a2 = A()
switch a1 {
case a2: //do something 
}

Although we rarely write codes like these, I'm still very curious about how switch statement works in Swift.

1 Answer 1

3

As explained in Expression Patterns,

The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator.

You can define func ~=(lhs: A, rhs: A) if you wish for your custom type to be used in a switch statement.

But I'd also recommend simply using the Equatable protocol, implementing ==, and then you can write if a1 == a2 { ... }.

In fact, the standard library provides

public func ~=<T : Equatable>(a: T, b: T) -> Bool

So if you conform to Equatable, you don't need to provide your own ~=.

Sign up to request clarification or add additional context in comments.

6 Comments

== is provided for NSObject subclasses, I believe. It uses isEqual(_:).
It seems that I can write if a1 == a2 { ... } even if class A doesn't conform to Equatable protocol , and overload == operator is enough. In conclusion, do you mean any type which overloads their ~= operator can be compared in switch statement?
You can ⌘-click on the == operator to see where it's defined. Yes, ~= is what's used for switch statements.
== is defined in Swift module. I am still not clear about if I have to conform to Equatable explicitly or just overload == operator is enough. Also, what do you mean by isEqual(_:), I think it is a method in Objective-C
If you are already providing == then I would recommend conforming to Equatable because you'll get access to various extensions such as SequenceType's split and startsWith etc. I also updated my answer — if you are Equatable, you don't need a custom ~=.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.