简体   繁体   English

if-else undefined变量编译错误

[英]if-else undefined variable compile error

if someCondition() {
    something := getSomething()
} else {
    something := getSomethingElse()
} 

print(something)

in this code example, compiler gives an undefined: something error. 在这个代码示例中,编译器给出了一个undefined: something错误。 Since this is an if else statement something variable will be defined in the runtime, but compiler fails detect this. 由于这是一个if else语句,因此将在运行时定义something变量,但编译器无法检测到这一点。

How can I avoid this compile error, also will this be fixed in the next versions? 如何避免此编译错误,这也将在下一个版本中修复?

The two something variables are two different variables with different scopes. 这两个something变量是与不同的范围两个不同的变量。 They do not exist outside the if/else block scope which is why you get an undefined error. 它们不存在于if / else块作用域之外,这就是为什么会出现未定义的错误。

You need to define the variable outside the if statement with something like this: 您需要在if语句之外定义变量,如下所示:

var something string

if someCondition() {
    something = getSomething()
} else {
    something = getSomethingElse()
} 

print(something)

In your code fragment, you're defining two something variables scoped to each block of the if statement. 在你的代码片段,你定义两个something范围的if语句的每个块的变量。

Instead, you want a single variable scoped outside of the if statement: 相反,您需要在if语句之外的单个变量:

var something sometype
if someCondition() {
    something = getSomething()
} else {
    something = getSomethingElse()
} 

print(something)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM