0

在对 JSON 进行编码时,我用一个if let语句来解包,但我想让一个变量全局可用

do {
  if
    let json = try JSONSerialization.jsonObject(with: data) as? [String: String], 
    let jsonIsExistant = json["isExistant"] 
  {
    // Here I would like to make jsonIsExistant globally available
  }

这甚至可能吗?如果不是这样,我可以if在这个里面做一个声明,但我认为这不是聪明的,甚至是不可能的。

4

2 回答 2

1

delclare jsonIsExistant 在你想要的地方。如果您正在制作 iOS 应用程序,请在上面viewDidLoad()创建变量

var jsonIsExistant: String?

然后在这一点上使用它

do {
    if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], 
    let tempJsonIsExistant = json["isExistant"] {
        jsonIsExistant = tempJsonIsExistant
    }
}

这可以像这样重写

do {
    if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] { 
        jsonIsExistant = json["isExistant"]
    }
} catch {
    //handle error
}

如果以第二种方式处理,那么您必须在使用前检查 jsonIsExistant 是否为 nil,或者您可以立即使用 ! 如果您确定每次成功成为 json 时它总会有一个字段“isExistant”。

于 2016-11-10T20:06:17.337 回答
1

if let将变量暴露给语句外部是没有意义的:


if let json = ... {
    //This code will only run if json is non-nil.
    //That means json is guaranteed to be non-nil here.
}
//This code will run whether or not json is nil.
//There is not a guarantee json is non-nil.

您还有其他一些选择,具体取决于您要执行的操作:


您可以将需要的其余代码json放在if. 您说您不知道嵌套if语句是否“聪明甚至可能”。它们是可能的,并且程序员经常使用它们。您也可以将其提取到另一个函数中:

func doStuff(json: String) {
    //do stuff with json
}

//...
if let json = ... {
    doStuff(json: json)
}

如果您知道JSON 不应该是nil,您可以使用以下命令强制解包!

let json = ...!

您可以使用guard语句使变量成为全局变量。里面的代码guard只会在json is nil时运行。guard语句的主体必须退出封闭范围,例如通过抛出错误、从函数返回或带有标记的 break:

//throw an error
do {
    guard let json = ... else {
        throw SomeError
    }
    //do stuff with json -- it's guaranteed to be non-nil here.
}



//return from the function 
guard let json = ... else {
    return
}
//do stuff with json -- it's guaranteed to be non-nil here.



//labeled break
doStuff: do {
    guard let json = ... else {
        break doStuff
    }
    //do stuff with json -- it's guaranteed to be non-nil here.
}
于 2016-11-10T20:10:41.683 回答