switch 语句在后台使用~= 运算符。所以这个:
let x = 2
switch x {
case 1: print(1)
case 2: print(2)
case 3..<5: print(3..<5)
default: break
}
脱糖:
if 1 ~= x { print(1) }
else if 2 ~= x { print(2) }
else if 3..<5 ~= x { print(3..<5) }
else { }
If you look at the standard library reference, it can tell you exactly what the ~= is overloaded to do: 包括范围匹配和等价的东西。 (不包括枚举大小写匹配,这是一种语言特性,而不是标准库中的函数)
您会发现它与左侧的直接布尔值不匹配。对于此类比较,您需要添加 where 语句。
除非...您自己重载 ~= 运算符。 (这通常不推荐)一种可能性是这样的:
func ~= <T> (lhs: T -> Bool, rhs: T) -> Bool {
return lhs(rhs)
}
这样就匹配了一个函数,该函数将左侧的布尔值返回到右侧的参数。以下是您可以使用它的类型:
func isEven(n: Int) -> Bool { return n % 2 == 0 }
switch 2 {
case isEven: print("Even!")
default: print("Odd!")
}
对于您的情况,您可能有如下语句:
switch someVar {
case isNegative: ...
case 0: ...
case isPositive: ...
}
但现在您必须定义新的isNegative 和isPositive 函数。除非你重载更多的运算符...
您可以将普通中缀运算符重载为柯里化前缀或后缀运算符。这是一个例子:
postfix operator < {}
postfix func < <T : Comparable>(lhs: T)(_ rhs: T) -> Bool {
return lhs < rhs
}
这将像这样工作:
let isGreaterThanFive = 5<
isGreaterThanFive(6) // true
isGreaterThanFive(5) // false
将它与前面的函数结合起来,你的 switch 语句可以如下所示:
switch someVar {
case 0< : print("Bigger than 0")
case 0 : print("0")
default : print("Less than 0")
}
现在,您可能不应该在实践中使用这种东西:它有点狡猾。您(可能)最好坚持使用where 声明。也就是说,
的switch语句模式
switch x {
case negative:
case 0:
case positive:
}
或
switch x {
case lessThan(someNumber):
case someNumber:
case greaterThan(someNumber):
}
似乎很常见,值得考虑。