Georg Weber
Georg Weber

Reputation: 45

Cannot find variable in scope

in Swift I need to use a variable which I created in a if/else outside of it. I made a little code just for showing the problem

let test = 0
if test == 0 {
    let a = "Test is 0"
} else {
    let a = "Test is not 0"
}

print(a)

the result is cannot find a in scope

I need the value of the variable outside of the if statement without creating the variable outside first. How I can do that please?

Upvotes: 2

Views: 3472

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51892

You can create the variable outside, even if it is a let variable as long it is assigned a value both in the if and else clause so it always gets set.

let test = 0
let a: String
if test == 0 {
    a = "Test is 0"
} else {
    a = "Test is not 0"
}

Upvotes: 5

Related Questions