英文:
if-else undefined variable compile error
问题
在这个代码示例中,编译器会报一个undefined: something
的错误。由于这是一个if else语句,something
变量将在运行时定义,但编译器无法检测到这一点。
你可以如何避免这个编译错误?这个问题在下一个版本中会被修复吗?
英文:
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?
答案1
得分: 1
两个 something
变量是具有不同作用域的两个不同变量。它们在 if/else 块作用域之外不存在,这就是为什么会出现未定义错误。
你需要在 if 语句之外定义该变量,可以像这样:
var something string
if someCondition() {
something = getSomething()
} else {
something = getSomethingElse()
}
print(something)
英文:
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)
答案2
得分: 1
在你的代码片段中,你定义了两个 something
变量,它们的作用域限定在 if 语句的每个块内。
相反,你想要一个作用域在 if 语句之外的单个变量:
var something sometype
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.
Instead, you want a single variable scoped outside of the if statement:
var something sometype
if someCondition() {
something = getSomething()
} else {
something = getSomethingElse()
}
print(something)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论