发布于 2015-06-14 02:01:09 | 164 次阅读 | 评论: 0 | 来源: 网络整理

表达式模式(Expression Pattern)

表达式模式代表了一个表达式的值。这个模式只出现在switch语句中的case标签中。

由表达式模式所代表的表达式用Swift标准库中的~=操作符与输入表达式的值进行比较。如果~=操作符返回true,则匹配成功。默认情况下,~=操作符使用==操作符来比较两个相同类型的值。它也可以匹配一个整数值与一个Range对象中的整数范围,正如下面这个例子所示:


let point = (1, 2)
switch point {
case (0, 0):
    println("(0, 0) is at the origin.")
case (-2...2, -2...2):
    println("((point.0), (point.1)) is near the origin.")
default:
    println("The point is at ((point.0), (point.1)).")
}
// prints "(1, 2) is near the origin.”

你可以重载~=操作符来提供自定义的表达式行为。例如,你可以重写上面的例子,以实现用字符串表达的点来比较point表达式。


// Overload the ~= operator to match a string with an integer
func ~=(pattern: String, value: Int) -> Bool {
    return pattern == "(value)"
}
switch point {
case ("0", "0"):
    println("(0, 0) is at the origin.")
case ("-2...2", "-2...2"):
    println("((point.0), (point.1)) is near the origin.")
default:
    println("The point is at ((point.0), (point.1)).")
}
// prints "(1, 2) is near the origin.”


表达式模式语法
表达式模式 → 表达式
 

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务