表達(dá)式模式代表了一個(gè)表達(dá)式的值。這個(gè)模式只出現(xiàn)在switch語句中的case標(biāo)簽中。
由表達(dá)式模式所代表的表達(dá)式用Swift標(biāo)準(zhǔn)庫中的~=操作符與輸入表達(dá)式的值進(jìn)行比較。如果~=操作符返回true,則匹配成功。默認(rèn)情況下,~=操作符使用==操作符來比較兩個(gè)相同類型的值。它也可以匹配一個(gè)整數(shù)值與一個(gè)Range對(duì)象中的整數(shù)范圍,正如下面這個(gè)例子所示:
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.”
你可以重載~=操作符來提供自定義的表達(dá)式行為。例如,你可以重寫上面的例子,以實(shí)現(xiàn)用字符串表達(dá)的點(diǎn)來比較point表達(dá)式。
// 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.”
表達(dá)式模式語法
表達(dá)式模式 → 表達(dá)式