Use of unresolved Identifier when using for loop i

2019-09-10 03:22发布

问题:

I am new to programming with swift and am confused as to why the program does not recognise what I have labeled as "test", claiming it is unresolved.

import UIKit

var rainfall = [38,94,142,149,236,305,202,82,139,222,178,103]
var raindays = [3,6,8,7,12,16,10,8,12,14,11,7]
let crit_raindays = 11
let et_raindays_lessthan_11 = 150
let et_raindays_morethan_11 = 120
let max_h2Ostore = 150
var evap_transpiration: [Int] = []


for i in raindays {
    if i <= 11 {
        var test = et_raindays_lessthan_11
    }
    else if i > 11 {
        var test = et_raindays_morethan_11
    }
    evap_transpiration.append(test)
}

The variable test does not seem to be assigned properly, I have no idea why. Error message: Use of unresolved identifier "test"

回答1:

When you declare a local variable in Swift, it will be accessible only after its declaration and in the the same scope. In your sample code: the first declaration will be accessible only inside the first if statement, and the second declaration will be accessible only inside the second one. The correct way is:

for i in raindays {
    var test = 0
    if i <= 11 {
       test = et_raindays_lessthan_11
    }
    else if i > 11 {
       test = et_raindays_morethan_11
    }

    evap_transpiration.append(test)
}

Even more, you don't need the second if, since if the first one is false, the second one will be always true. So, the code is:

for i in raindays {
    var test = 0
    if i <= 11 {
       test = et_raindays_lessthan_11
    }
    else {
       test = et_raindays_morethan_11
    }

    evap_transpiration.append(test)
}


回答2:

Try this:

var test: Int

for i in raindays {
  if i <= 11 {
    test = et_raindays_lessthan_11
  }
  else if i > 11 {
    test = et_raindays_morethan_11
  }
  evap_transpiration.append(test)
}

The reason is that you define test inside a block, so the scope is only internal to that block.



回答3:

You need to declare test outside the for loop. Here is what I have that works.

import UIKit

var rainfall = [38,94,142,149,236,305,202,82,139,222,178,103]
var raindays = [3,6,8,7,12,16,10,8,12,14,11,7]
let crit_raindays = 11
let et_raindays_lessthan_11 = 150
let et_raindays_morethan_11 = 120
let max_h2Ostore = 150
var evap_transpiration: [Int] = []
var test = 0

for i in raindays {
if i <= 11 {
    test = et_raindays_lessthan_11
}
else if i > 11 {
    test = et_raindays_morethan_11
}
evap_transpiration.append(test)
}


标签: xcode swift