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?

Many Thanks
There are two questions there:
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.
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 the original 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
Re-declaring the constant in the inner scope is not an error. All it does is hiding the constant from the outer scope, which is perfectly legal.
The problem happens because there is a code path, namely, the one through the else with a re-declaration, that leaves the outer constant uninitialized. That is the error the compiler reports.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With