Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redeclaring variables in functions

Tags:

scope

swift

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
    } ...
like image 707
Marmelador Avatar asked Oct 31 '25 20:10

Marmelador


2 Answers

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
like image 57
shallowThought Avatar answered Nov 02 '25 11:11

shallowThought


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
}
like image 36
Jack G. Avatar answered Nov 02 '25 10:11

Jack G.