Kian Cross
Kian Cross

Reputation: 1818

Why do I get the 'Use of unresolved identifier' error when writing this code in Swift?

I have the following code:

let FOO = true
if (FOO) {
    let BAR = "Off"
} else {
    let BAR = "On"
}
print(BAR)

My problem that is the line that says print(BAR) returns the error:

Use of unresolved identifier 'BAR'

From what I can see, there is no reason that this code shouldn't compile is there? The constant BAR will always be created so can always be printed to the console.

Upvotes: 1

Views: 1984

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

The scope of BAR is limited to the if/else so you can't refer to it later in the code.

But you can do

let foo = true
let bar: String
if (foo) {
    bar = "Off"
} else {
    bar = "On"
}
print(bar)

The compiler is able to realize that bar is assigned only once and before use, so this will compile just fine.

Upvotes: 9

Epic Defeater
Epic Defeater

Reputation: 2147

This is because BAR is a local variable of only the if and else statement, so try this code instead.

let FOO = true
var BAR = ""
if (FOO) {
   BAR = "Off"
} else {
   BAR = "On"
}
print(BAR)

Upvotes: 1

Related Questions