If you are working with an NSFileHandle that encapsulated a pipe, it was possible to use a @try-@catch block to handle a failed write.

In this example, fileHandle could represent an open socket, with the SIGPIP thrown if the client disconnects unexpectedly and the pipe is closed:

@try
{
  [fileHandle writeData:fileData];
}
@catch (NSException *exception)
{
  // Ignore the SIGPIP
}
@finally
{
  CFRelease(fileData);
}

Unfortunately in Swift 2.0 this isn’t possible; the analogous try-catch doesn’t capture signals.

How can we can handle this in Swift?

My solution has been to fall back to the native BSD APIs. When creating the socket with CFSocketCreate prevent SIGPIP from being thrown by setting the option:

var no_sig_pipe: Int32 = 1
setsockopt(CFSocketGetNative(socket),
SOL_SOCKET,
SO_NOSIGPIPE,
&no_sig_pipe,
socklen_t(sizeof(Int32)))

Then assuming the write is performed in a separate method, we can use a guard to perform a dummy write before the socket is used:

guard (write(fileHandle.fileDescriptor, nil, 0) == 0) else {
  CFRelease(fileData)
    return false
  }
fileHandle.writeData(fileData)

If the socket is closed then the guard will cleanup and return.