Ios 如何在swift中检查nil变量并避免应用程序崩溃?

Ios 如何在swift中检查nil变量并避免应用程序崩溃?,ios,swift,swifty-json,Ios,Swift,Swifty Json,我的字符串声明为 var firstName = String() 我从解析的JSON内容中赋值,比如 firstName = json["first_name"].stringValue 但有时,JSON响应中可能有空值,应用程序正在崩溃,我阅读了guard语句和if语句来检查空值,但这需要更改声明格式,在不更改声明格式的情况下,无法找到正确的方法来处理此错误 由于我已经用相似的格式声明了我应用程序中的所有变量,更改需要时间,我即将上载我的应用程序,这是我的第一个swift应用程序,如果我

我的字符串声明为

var firstName = String()
我从解析的JSON内容中赋值,比如

firstName = json["first_name"].stringValue
但有时,JSON响应中可能有空值,应用程序正在崩溃,我阅读了guard语句和if语句来检查空值,但这需要更改声明格式,在不更改声明格式的情况下,无法找到正确的方法来处理此错误


由于我已经用相似的格式声明了我应用程序中的所有变量,更改需要时间,我即将上载我的应用程序,这是我的第一个swift应用程序,如果我的声明格式错误,请回答原因,有人能帮我解决这个问题吗?

你可以通过以下方式完成:

if let dictionary = json {
    if let fName = dictionary["first_name"] {
        firstName = fName as? String
    }
}

你也可以用守卫声明

guard let firstName = json["first_name"] else {
    print("FirstName is Empty")
    return
}
或者你也可以去看看

if let firstName = json["first_name"] {
    //Your code goes here
}

您可以使用下一个语句:

guard let firstName = json["first_name"].stringValue else { // Do sth if nil }
// Do sth if not nil
或者您可以使用您编写的语句,但您应该检查变量
firstName
如下:

guard firstName != nil else { // Do sth if nil }
// Do sth if not nil

自Swift 4起的代码:

请记住,当您使用“.stringValue”时,它几乎与使用“!”相同,后者将强制在nil上崩溃

    if let firstName = json["first_name"]as? String {
        //do stuff like
        self.firstName = firstName
    }
这会将其展开到可以获取值的位置(如果该值不是null并且可以是字符串)

Guard let’s在这方面做得非常好,因为您可以在开始时解释它,并且您可以假设它对于整个范围不是可选的

    guard let firstName = json["first_name"]as? String else {return}
    self.firstName = firstName
此外,您可以始终在一行中检查空值,并在出现nil值时指定默认值

    self.firstName = (json["first_name"]as? String) ?? "Default String"

我建议您使用
SwiftyJSON
。函数
stringValue
始终返回
String
对象。不可能是零。这听起来像是响应数据,它不是有效的JSON格式,所以它崩溃了

我的代码片段

// Alarmofire + SwiftyJSON
let request: DataRequest = ...//< Configure Alarmofire DataRequest
request.response() { (resp) in
     if let error = resp.error {
        // TODO: Error handle
        return
     }

     if (response.data == nil) {
         // TODO: error handle for empty data?
         return
     }

     assert(response.data != nil, "In this place, the `data` MUST not be nil.")
     let json = try? JSON(data: response.data!)
     if (json == nil) {
         // TODO: Error handle for invalid JSON format.
         // If json is nil, then `json["first_name"]` will lead to crash.
         return
     }

     // TODO: parse json object
     let firstNameStr = json["first_name"].stringValue

}
//Alarmofire+SwiftyJSON
let request:DataRequest=…/<配置Alarmofire DataRequest
中的request.response(){(resp)
如果let error=resp.error{
//TODO:错误句柄
返回
}
如果(response.data==nil){
//TODO:空数据的错误句柄?
返回
}
assert(response.data!=nil,“在这里,`data`不能为nil。”)
让json=try?json(数据:response.data!)
if(json==nil){
//TODO:无效JSON格式的错误句柄。
//如果json为nil,那么`json[“first_name”]`将导致崩溃。
返回
}
//TODO:解析json对象
让firstNameStr=json[“first_name”].stringValue
}

您可以使用Guard语句检查此链接,如果json[“first\u name”]返回可选,则使用可选绑定。像这样,如果让firstName=json[“first_name”]{//get your string here}请添加一些上下文。json的类型是什么?你从哪里得到它?你能添加崩溃报告吗?SwiftyJSON有一个可选的“.string”getter。“.stringValue”getter是非可选的。
// Alarmofire + SwiftyJSON
let request: DataRequest = ...//< Configure Alarmofire DataRequest
request.response() { (resp) in
     if let error = resp.error {
        // TODO: Error handle
        return
     }

     if (response.data == nil) {
         // TODO: error handle for empty data?
         return
     }

     assert(response.data != nil, "In this place, the `data` MUST not be nil.")
     let json = try? JSON(data: response.data!)
     if (json == nil) {
         // TODO: Error handle for invalid JSON format.
         // If json is nil, then `json["first_name"]` will lead to crash.
         return
     }

     // TODO: parse json object
     let firstNameStr = json["first_name"].stringValue

}