我正在使用SwiftyJSON调用一些API并获取一些数据。当我使用:
if let variable = json["response"]["fieldname"] {
} else {
println("error")
}
以后我不能使用该变量,例如将值附加到数组中。例如:
if let variable1 = json["response"]["fieldname1"] {
} else {
println("error")
}
if let variable2 = json["response"]["fieldname2"] {
} else {
println("error")
}
var currentRecord = structure(variable1, variable2) ---> This line returns an error (use of unresolved identifier variable1) as not able to find variable1 or variable2
myArray.append(currentRecord)
我该如何解决这个问题?
if let
的作用域位于其后面的括号内:
if let jo = joseph {
// Here, jo is in scope
} else {
// Here, not in scope
}
// also not in scope
// So, any code I have here that relies on jo will not work
在Swift 2中,添加了一个新的声明guard
,它似乎正是你想要的行为:
guard let jo = joseph else { // do something here }
// jo is in scope
不过,如果你被Swift 1卡住了,一个简单的方法可以让你在没有厄运金字塔的情况下打开这些变量:
if let variable1 = json["response"]["fieldname1"], variable2 = json["response"]["fieldname2"] {
var currentRecord = structure(variable1, variable2)
myArray.append(currentRecord)
} else {
println("error")
}
@oisdk已经解释了if let
定义的变量的作用域仅在该语句的大括号内。
这就是您想要的,因为如果它的if let
语句失败,那么该变量是未定义的。iflet的全部目的是安全地打开可选项,这样在大括号内,就可以确保变量是有效的。
另一个解决问题的方法(Swift 1.2(是使用多个iflet语句:
if let variable1 = json["response"]["fieldname1"],
let variable2 = json["response"]["fieldname2"]
{
//This code will only run if both variable1 and variable 2 are valid.
var currentRecord = structure(variable1, variable2)
myArray.append(currentRecord)}
else
{
println("error")
}
您的代码检查变量2时,即使变量1也总是失败但是导致(已编辑!(而不是错误。
您可以在同一行中检查和分配两个变量。只有当两个变量都不是零时,才会执行"true"分支
let response = json["response"]
if let variable1 = response["fieldname1"], variable2 = response["fieldname2"] {
let currentRecord = structure(variable1, variable2)
myArray.append(currentRecord)
} else {
println("error")
}