为什么我不能用swift更改if语句中的变量? [英] why i can't change a variable in an if statement with swift?
本文介绍了为什么我不能用swift更改if语句中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简短的问题。为什么我不能在if语句中更改var Test的值?
I have a short question. Why can't I change the value of the var Test in a if statement?
if Status == 1{
var Test = 1
}
else{
var Test = 2
}
println(Test) // Error: Use of unresolved identifier 'Test'
推荐答案
因为测试
超出了您的范围。 测试
在两个不同的 if(){}
范围内定义。
在 if()
范围之外声明测试
将允许您在更广泛的范围内访问它。
because Test
is out of your scope. Test
is defined in two different if(){}
scopes.
Declaring Test
outside of the if()
scope will allow you to access it in a broader scope.
var Test :Int
if Status == 1{
Test = 1
}
else{
Test = 2
}
println(Test)
编辑:无法推断出未声明的变量(Test),因此建议指定变量类型(:= Int表示整数)。如果存在任何其他类型的值,则会显示错误。
A undeclared variable (Test) cannot be inferred from, therefore recommend to specify variable type (:=Int for integer). If there is any other type of value, an error will be displayed.
这篇关于为什么我不能用swift更改if语句中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文