本文介绍了为什么我不能快速更改 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'

推荐答案

因为 Test 超出了您的范围.Test 在两个不同的 if(){} 范围内定义.在 if() 范围之外声明 Test 将允许您在更广泛的范围内访问它.

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.

这篇关于为什么我不能快速更改 if 语句中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:13
查看更多