在本地范围之外声明的变量仍在范围内可用/可访问.因此,我想如果我重新声明范围内的变量,编译器会告诉我重新声明错误.
在以下代码片段中,常量tipPercentage在if范围之外声明,并在if范围内设置
let totallBill = 95.00
let tipPercentage: Double
let rating = 3
if rating == 5 {
tipPercentage = 0.25
} else if rating >= 3 {
tipPercentage = 0.15
} else {
let tipPercentage = 0.10 //# error caused by the let
}
let totalPaid = totallBill + totallBill * tipPercentage
Run Code Online (Sandbox Code Playgroud)
问题
我在if范围内重新声明了常量.我认为它会告诉重新声明变量错误,但相反,它给出了" constant "tipPercentage" used before being initialized." 为什么会这样?
非常感谢
那里有两个问题:
为什么你没有得到一些"重新声明"的错误?
这是因为如果在同一范围内重新声明变量,则只会出现重新声明错误.但是你的else子句是一个更窄的范围,所以let tipPercentage它定义了另一个常量,其名称恰好与原始名称相同tipPercentage,但其范围仅限于该else子句.
不过,我本可以预料到,这个新的窄范围tipPercentage常数已被宣布但从未使用过.
你为什么在初始化之前得到"常量'tipPercentage'"错误?
你得到了这个,因为第三个子句(最后一个else子句)定义了一个巧合地调用的新局部常量tipPercentage,但是tipPercentage在第三个路径中没有触及原始子句.所以警告告诉你在上面有一个执行路径if- else没有设置原始语句的语句tipPercentage.
为了帮助澄清,您的代码段相当于:
let totallBill = 95.00
let tipPercentage: Double
let rating = 3
if rating == 5 {
tipPercentage = 0.25
} else if rating >= 3 {
tipPercentage = 0.15
} else {
let foo = 0.10 // this was coincidentally called `tipPercentage`, but since this is yet another a local constant of even narrower scope, it's equivalent to using a completely different name
}
let totalPaid = totallBill + totallBill * tipPercentage
Run Code Online (Sandbox Code Playgroud)