不要尝试赶快2 [英] do try catch swift 2

查看:88
本文介绍了不要尝试赶快2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何转移if_else错误处理以尝试成功捕获感到困惑.

HI i am a little confused about how to transfer if_else error handling to do try catch successfully.

这是我的代码.

let error : NSError?
if(managedObjectContext!.save()) {
    NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    
    if error != nil {
       print(error?.localizedDescription)
    }
}
else {
    print("abort")
    abort()
}

现在我像这样转换为Swift 2.0

and now i converted to swift 2.0 like this

do {
   try managedObjectContext!.save()
}
catch {
     NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
     print((error as NSError).localizedDescription)
}

我对在哪里打印中止并执行abort()函数感到困惑

I am confused about where to print abort and do the abort() function

有什么主意吗?非常感谢

Any idea~? Thanks a lot

推荐答案

重写代码以使其与原始代码相同

Rewriting your code to work the same as your original code

do {
   try managedObjectContext!.save()

   //this happens when save did pass
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    

   //this error variable has nothing to do with save in your original code
   if error != nil {
       print(error?.localizedDescription)
   }
}
catch {
   //this happens when save() doesn't pass
   abort()
}

您可能想写的是以下内容:

what you probably want to write is the following:

do {
   try managedObjectContext!.save()

   //this happens when save did pass
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    
}
catch let saveError as NSError {
   //this happens when save() doesn't pass
   print(saveError.localizedDescription)
   abort()
}

这篇关于不要尝试赶快2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆