【问题标题】:Re-declare variable, Xcode tells it used before initializing, why not the re-declaration error?重新声明变量,Xcode在初始化之前告诉它使用,为什么不是重新声明错误?
【发布时间】:2016-07-30 18:02:19
【问题描述】:

在本地范围之外声明的变量在范围内仍然可用/可访问。因此,我想如果我在范围内重新声明变量,编译器会告诉我一个重新声明错误。

在下面的代码sn-p中,常量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

问题

我在 if 范围内重新声明了常量。我以为它会告诉一个redeclare variable error,但它却给出了“constant "tipPercentage" used before being initialized.”这是为什么?

非常感谢

【问题讨论】:

    标签: swift xcode scope


    【解决方案1】:

    这里有两个问题:

    1. 为什么没有出现“重新声明”错误?

      这是因为只有在相同范围内重新声明变量时才会出现重新声明错误。但是您的else 子句范围更窄,因此let tipPercentage 定义了另一个常量,其名称巧合地与原始tipPercentage 相同,但其范围仅限于else 子句。

      不过,我本来预计会收到另一个警告,即这个新的窄范围 tipPercentage 常量已声明但从未使用过。

    2. 为什么会出现“在初始化之前使用的常量 'tipPercentage'”错误?

      你得到这个是因为第三个子句(最后的else 子句)定义了一个新的局部常量,巧合地称为tipPercentage,但在第三个路径中没有触及原来的tipPercentage。所以警告是告诉你上面的if-else 语句中没有设置原始tipPercentage 的执行路径。


    为了帮助澄清,您的代码 sn-p 相当于:

    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
    

    【讨论】:

    • 非常感谢您的帮助和解释
    【解决方案2】:

    在内部范围内重新声明常量不是错误。它所做的只是将常量隐藏在外部范围之外,这是完全合法的。

    问题的发生是因为有一个代码路径,即通过 else 并重新声明的路径,导致 outer 常量未初始化。这是编译器报告的错误。

    【讨论】:

    • 非常感谢您的解释")
    猜你喜欢
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2021-02-13
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多