Swift2中的switch语句可以比较哪种类型的值

Which type of value can be compared in switch statement in Swift2

我想知道在switch语句中可以比较哪种类型的值。官方文档说:

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

还有什么事吗?我可以在 switch 语句中比较 class 类型吗?

假设我有一个 class A:

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

然后我可以检查 class A 的两个对象是否相等。但是我还是不能这样做:

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

虽然我们很少写这样的代码,但我还是很好奇switch语句在Swift中是如何工作的。

Expression Patterns

中所述

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

如果您希望在 switch 语句中使用您的自定义类型,您可以定义 func ~=(lhs: A, rhs: A)

但我也建议简单地使用 Equatable 协议,实现 ==,然后你可以写 if a1 == a2 { ... }.

其实标准库提供

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

因此,如果您符合 Equatable,则无需提供自己的 ~=