Search code examples
swift2do-catch

do try catch swift 2


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

Here is my code.

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

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

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

Any idea~? Thanks a lot


Solution

  • 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()
    }