why i can't change a variable in an if statement with swift?

前端 未结 1 443
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 07:44

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
}

printl         


        
相关标签:
1条回答
  • 2020-12-12 08:04

    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) 
    

    EDIT: 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.

    0 讨论(0)
提交回复
热议问题