Consider this class:
@implementation SomeObjectiveClass
+ (BOOL)someClassMethodWithError:(NSError **)error {
// some something that
if (everythingOk) {
return true;
} else {
if (error) {
*error = [NSError errorWithDomain:kMyDomain code:kSomeErrorCode userInfo:@{NSLocalizedDescriptionKey : @"Some error message"}];
}
return false;
}
}
- (BOOL)someInstanceMethodWithError:(NSError **)error {
// some something that
if (everythingOk) {
return true;
} else {
if (error) {
*error = [NSError errorWithDomain:kMyDomain code:kSomeOtherErrorCode userInfo:@{NSLocalizedDescriptionKey : @"Some error message"}];
}
return false;
}
}
@end
You can then catch those errors like so:
do {
try SomeObjectiveClass.someClassMethod()
// or
let object = SomeObjectiveClass()
try object.someInstanceMethod()
} catch {
print("Recovered \(error) from Swift!")
}
Note, this catching of errors should not be confused with exception handling which we used to be able to do in Objective-C. Exceptions should be eliminated during the development process. The above is for legitimate runtime errors (e.g. failed network request or some other error that might occur due to conditions outside of the programmer's control).
To quote from Using Swift with Cocoa and Objective-C:
Although Swift error handling resembles exception handling in Objective-C, it is entirely separate functionality. If an Objective-C method throws an exception during runtime, Swift triggers a runtime error. There is no way to recover from Objective-C exceptions directly in Swift. Any exception handling behavior must be implemented in Objective-C code used by Swift.
someMethodtakes anNSError **parameter, when you call that from Swift 2, that behaves like a method that throws an error.do-try-catchmechanism in Swift is for catching errors, not exception handling.