Let 在这个例子中没有用,可以去掉:
我修改了 OP 引用的代码(可在 GuidedTour 中排除 let x,以表明 let x完全没用。可读性也得到了提高,因为 x 是不再存在。这是 OP (Mani) 问题的核心:为什么使用 let?答案是,在这种情况下,您不应该这样做。
使用x 很混乱,这是什么意思?最后,为什么需要重新声明一个常量(vegetable 为x),因为它不会改变。没意义!
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case vegetable where vegetable.hasSuffix("pepper"):
print("Is it a spicy \(vegetable)?")
default:
print("Everything tastes good in soup.")
}
// Prints "Is it a spicy red pepper?"
简单的切换语句
首先,where 关键字允许你在每个 case 中执行任意代码,这样你就可以在不同的 case 条件下运行不同的代码。如果没有这个,switch 语句只会检查参数和 case 之间的 相等性。
有限:每个case条件都比较switch语句条件(age)和case表达式,因为where没有用到:
switch age {
case 20:
print("He is 20")
case 21:
print("He is 21")
print("or... he is \(age)")
default:
print("He is in an unknown age group.")
}
更好:我们现在可以在 case 表达式中执行代码,因为使用了 where(注意没有使用 let)。这允许使用范围和更复杂的表达式,这将缩短 switch 语句的大小:
switch age {
case let age where age < 20:
print("He is younger than 20")
case age where 20 < age && age < 30:
print("He is between 20 and 30")
print("\(age)")
default:
print("He is in an unknown age group.")
}
没有获得任何好处:创建一个新的常量来保存确切的值作为切换参数是没有用的:
switch age {
case let age where age < 20:
print("He is younger than 20")
case let age_2 where 20 < age_2 && age_2 < 30:
print("He is between 20 and 30")
print("\(age == age_2) is True, and will always be True. Useless!")
default:
print("He is in an unknown age group.")
}
因此,使用let x ... 重新声明开关条件(age 或vegetable)是完全没用的。
let 真正有用的地方:
let vegetable 可以在这里派上用场,当我们没有传递给 switch 的值的变量或常量时:
func getVegetable() -> String {
return "Sweet Potato"
}
switch(getVegetable()) {
case "Pepper":
print("Spicy!")
case let vegetable where vegetable.hasSuffix("Potato"):
print("eww potatoes!")
default:
print("Unknown vegetable")
}
当你想解包传递给 switch 语句的参数时,它更有用:
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// Prints "on the x-axis with an x value of 2"
source (read value binding section)。它实际上允许您匹配 switch 参数的其余部分,并声明一个更有用的变量。
我会将此功能称为变量解包或开关解包或开关解包或别名或部分匹配 而不是值绑定。当您声明任何变量时,您也将值绑定到该变量......“值绑定”是一个无意义/宽泛的名称。