Why does redeclaring output inside this if-statement not generate an error?
let output = 0
if counter < message.count {
    let output = counter //This should throw an error, right?
    counter += 1
} ...
The scope inside the if-statement knows about output as proven here, when trying to change the value of output instead of re-declaring it:
let output = 0
    if counter < message.count {
        output = counter //ERROR: Cannot assign to value: 'output' is a 'let' constant
        counter += 1
    } ...
                There is no error because it is perfectly legal to declare a variable inside a closure with the same name of a variable which has been declared outside of the closure. It shadows the "outside declared variable".
In case your sample code is inside a class you could still access the "outside declared variable" using self:
class Foo {
    let output = 0
    func baa() {
        let output = 1
        print(output)
        print(self.output)
    }
}
Using this:
let foo = Foo()
foo.baa()
prints:
1
0
                        let output = counter is declaring a new variable (output) in the scope of the if statement, which has nothing to do with the output variable declared outside.
Edit
The code extract below illustrates that the output variables are not the same, despite their name. The value that gets changed is the one of the local output variable, not the one outside.
var message = [String]()
let output = 2
var counter = -1
if counter < message.count {
    let output = counter //This should throw an error, right?
    print("local output value is:\(output)") // here the local output value is -1 not 2.
    counter += 1
}
                        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