Reputation: 3480
if someCondition() {
something := getSomething()
} else {
something := getSomethingElse()
}
print(something)
in this code example, compiler gives an undefined: something
error. Since this is an if else statement something
variable will be defined in the runtime, but compiler fails detect this.
How can I avoid this compile error, also will this be fixed in the next versions?
Upvotes: 0
Views: 307
Reputation: 43899
In your code fragment, you're defining two something
variables scoped to each block of the if statement.
Instead, you want a single variable scoped outside of the if statement:
var something sometype
if someCondition() {
something = getSomething()
} else {
something = getSomethingElse()
}
print(something)
Upvotes: 2
Reputation: 90736
The two something
variables are two different variables with different scopes. They do not exist outside the if/else block scope which is why you get an undefined error.
You need to define the variable outside the if statement with something like this:
var something string
if someCondition() {
something = getSomething()
} else {
something = getSomethingElse()
}
print(something)
Upvotes: 1