如果错误 == nil 解析 swift

if error == nil parse swift

如果出现问题,我正在尝试检查何时将对象保存到我的解析服务。但我有两个选择,我有三个选择,但我不知道有什么区别。我有这三个选项(if error == nil,或 if object != nil,或 if error == nil and object != nil)。我应该使用哪一个。谢谢

选项 #1

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil{
    }
)}

选项 #2

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if object != nil{
    }
)}

选项#3

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil && object != nil{
    }
)}

最好对成功和失败使用不同的处理程序:

func saveInBackground(success: () -> Void, failure: (Error?) -> Void) {
    /* do whatever you need */
    if saved {
        success()
    } else {
        failure(saveError)
    }
}

saveInBackground(success: {
    /* saving was succeed */
}, failure: { (error) in
    /* saving was failed */
})

保存操作成功时绝不会出现错误,根据一般经验,这取决于您实施的后续步骤。 None 该方法无效,我仍然建议您在检查错误之前检查“快乐值”、对象、成功 dtc...

我建议并鼓励你使用 guard 语句,它是为这种情况而设计的。

    //Always safely unwrap optional value:
    if let user = PFUser.current(){

    user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in

        guard success, error == nil else {
        //handle error somehow...(print or whatever...)
        return
         }
       //Continue here as everything is fine...

    )}
}