2

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?

1 Answer 1

5

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"
}
Sign up to request clarification or add additional context in comments.

4 Comments

I did not know this... very interesting and helpful. Surprised I don't see this used more often in tutorials and code samples. Is it not advised?
Not sure why it is not used more because it is a very useful tool and also if you make a mistake, say forget the else in this case, the compiler will generate an error so it's perfectly safe.
This I know. But like I sad in the description, I would like to resolve this without declare the variable outside
@GeorgWeber I think you need to learn the basics about variable declaration, you can never use a variable outside of the scope that it was declared in. A variable declared in a function can only be used in that function, a variable declared within an if clause can only be used inside that clause and so on. So what you are asking is impossible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.