我是swift编程的新手,我很困惑为什么程序无法识别我标记为" test",声称它没有得到解决。
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)
}
变量测试似乎没有正确分配,我不知道为什么。 错误消息:使用未解析的标识符&#34; test&#34;
答案 0 :(得分:2)
当你在Swift中声明一个局部变量时,它只能在声明后和相同的范围内访问。在您的示例代码中:第一个声明只能在第一个if
语句中访问,第二个声明只能在第二个声明中访问。
正确的方法是:
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)
}
更重要的是,你不需要第二个if,因为如果第一个是假,第二个将永远为真。所以,代码是:
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)
}
答案 1 :(得分:0)
试试这个:
Ord a => a
原因是您在块内定义测试,因此范围仅在该块的内部。
答案 2 :(得分:0)
您需要在for循环之外声明测试。这就是我的工作原理。
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)
}