SLN SLN - 4 months ago 7
Swift Question

Re-declare variable, Xcode tells it used before initializing, why not the re-declaration error?

Variables declared outside local scope is still available/accessible inside the scope. Therefore, I guess if I redeclare the variable inside the scope the compiler would tell me a redeclaration error.

In the following code snippet, the constant

tipPercentage
is declared outside the if scope and been set inside the if scope

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


Problem

I redeclared the constant inside the if scope. I thought it will tell a redeclare variable error, but instead, it gave out the "
constant "tipPercentage" used before being initialized.
" Why is that?

enter image description here

Many Thanks

Rob Rob
Answer

There are two questions there:

  1. Why didn't you get some "redeclare" error?

    This is because you only get redeclaration errors if you redeclare a variable at the same scope. But your else clause is a more narrow scope, so the let tipPercentage is defining another constant whose name is coincidentally the same as the original tipPercentage, but whose scope is limited within that else clause.

    I would have expected, though, another warning that this new narrow-scoped tipPercentage constant was declared but never used.

  2. Why did you get the "constant 'tipPercentage' used before being initialized" error?

    You got this because that third clause (the final else clause) defined a new local constant coincidentally called tipPercentage, but the original tipPercentage is not touched in this third path. So the warning is telling you that there is a path of execution in the above if-else statements that didn't set tipPercentage.


To help clarify, your code snippet is equivalent to:

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
Comments