switch 语句中的常量绑定实际上做了什么?
What does constant binding in switch statements actually do?
我不太清楚 let
是如何在 switch
语句中使用的。
考虑一下:
let greeting = (1,10)
switch greeting {
case let (x,y) where x == y:
print("hello")
case (x,y) where x < y: //error here
print("what's up")
default: "No match"
}
根据 Apple docs:
[...] patterns in a case can also bind constants using the let keyword (they can also bind variables using the var keyword). These constants (or variables) can then be referenced in a corresponding where clause and throughout the rest of the code within the scope of the case. That said, if the case contains multiple patterns that match the control expression, none of those patterns can contain constant or variable bindings.
我的例子绑定的元组(x, y)
是什么,为什么不能再次引用?
来自 Swift 文档的引用:
... can then be referenced in a corresponding where clause and throughout
the rest of the code within the scope of the case.
所以第一种情况
case let (x,y) where x == y:
print("hello")
greeting
(即元组 (1, 10)
)与
模式
let (x,y) where x == y
如果匹配,x
绑定到第一个元组元素
y
到第二个。
此绑定仅限于第一种情况的范围,
并且不能用于第二种或其他情况。
为了编译你的代码,为第二个添加另一个 let
绑定
案例:
switch greeting {
case let (x,y) where x == y:
print("\(x) is equal to \(y)")
case let (x,y) where x < y:
print("\(x) is less than \(y)")
default:
print("No match")
}
我不太清楚 let
是如何在 switch
语句中使用的。
考虑一下:
let greeting = (1,10)
switch greeting {
case let (x,y) where x == y:
print("hello")
case (x,y) where x < y: //error here
print("what's up")
default: "No match"
}
根据 Apple docs:
[...] patterns in a case can also bind constants using the let keyword (they can also bind variables using the var keyword). These constants (or variables) can then be referenced in a corresponding where clause and throughout the rest of the code within the scope of the case. That said, if the case contains multiple patterns that match the control expression, none of those patterns can contain constant or variable bindings.
我的例子绑定的元组(x, y)
是什么,为什么不能再次引用?
来自 Swift 文档的引用:
... can then be referenced in a corresponding where clause and throughout the rest of the code within the scope of the case.
所以第一种情况
case let (x,y) where x == y:
print("hello")
greeting
(即元组 (1, 10)
)与
模式
let (x,y) where x == y
如果匹配,x
绑定到第一个元组元素
y
到第二个。
此绑定仅限于第一种情况的范围, 并且不能用于第二种或其他情况。
为了编译你的代码,为第二个添加另一个 let
绑定
案例:
switch greeting {
case let (x,y) where x == y:
print("\(x) is equal to \(y)")
case let (x,y) where x < y:
print("\(x) is less than \(y)")
default:
print("No match")
}