Swift 2.2 and Objective-C Interoperability in Error Handling
This appears to be happening because, in Swift 2.2, Objective-C methods that take a NSError **
for their last parameter are converted to the Swift throws
method equivalent.
You can find more information on this topic on this page, using the 3rd and 4th sections, excerpted below.
Error Handling (excerpt)
In Cocoa, methods that produce errors take an NSError
pointer parameter as their last parameter, which populates its argument with an NSError
object if an error occurs. Swift automatically translates Objective-C methods that produce errors into methods that throw an error according to Swift’s native error handling functionality.
For example, consider the following Objective-C method from NSFileManager
:
- (BOOL)removeItemAtURL:(NSURL *)URL
error:(NSError **)error;
In Swift, it’s imported like this:
func removeItemAtURL(URL: NSURL) throws
Catching and Handling an Error (excerpt)
In Objective-C, error handling is opt-in, meaning that errors produced by calling a method are ignored unless an error pointer is provided. In Swift, calling a method that throws requires explicit error handling.
Here’s an example of how to handle an error when calling a method in Objective-C:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *fromURL = [NSURL fileURLWithPath:@"/path/to/old"];
NSURL *toURL = [NSURL fileURLWithPath:@"/path/to/new"];
NSError *error = nil;
BOOL success = [fileManager moveItemAtURL:URL toURL:toURL error:&error];
if (!success) {
NSLog(@"Error: %@", error.domain);
}
And here’s the equivalent code in Swift:
let fileManager = NSFileManager.defaultManager()
let fromURL = NSURL(fileURLWithPath: "/path/to/old")
let toURL = NSURL(fileURLWithPath: "/path/to/new")
do {
try fileManager.moveItemAtURL(fromURL, toURL: toURL)
} catch let error as NSError {
print("Error: \(error.domain)")
}
Additionally, you can use catch clauses to match on particular error codes as a convenient way to differentiate possible failure conditions:
do {
try fileManager.moveItemAtURL(fromURL, toURL: toURL)
} catch NSCocoaError.FileNoSuchFileError {
print("Error: no such file exists")
} catch NSCocoaError.FileReadUnsupportedSchemeError {
print("Error: unsupported scheme (should be 'file://')")
}
Question-specific Code
In this code example, this means that, in Swift 2.2, the enableBroadcast(error:)
method of GCDAsyncUdpSocket
would be enableBroadcast() throws
and would need to use an explicit do-catch
.
Similarly, the beginReceiving()
method of GCDAsyncUdpSocket
would turn into beginReceiving() throws
and would also require the use of a do-catch
.