if let variable - 使用未解析的标识符

时间:2015-07-03 11:17:52

标签: ios json swift swifty-json

我使用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)

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

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")
}

答案 1 :(得分:1)

@oisdk已经解释过if let定义的变量的范围只在该语句的大括号内。

这就是你想要的,因为如果它if let语句失败,那么变量是未定义的。如果let的全部要点是安全地展开你的选项,那么在大括号内,你可以确定变量是有效的。

你的问题的另一个解决方案(在Swift 1.2中)是使用多个if if语句:

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 :(得分:0)

您的代码检查变量2,即使变量1也失败。 但是导致(编辑!)错误。

您可以在同一行中检查并分配两个变量。只有当两个变量都不是nil

时,才会执行“true”分支
let response = json["response"]
if let variable1 = response["fieldname1"],  variable2 = response["fieldname2"] {
  let currentRecord = structure(variable1, variable2)
  myArray.append(currentRecord)
} else {
  println("error")
}
相关问题