Throw Coalescing Operator

I'd really like syntax for do/try/catch which is as compact as nil coalescing in Swift. And so I put together a working implementation which I'd like to refine further. So far I have !! defined as my operator much like ?? for nil coalescing so it is familiar. The left operand would the work while the right would handle the error.

The goal could be this syntax which collects both of these expressions.

try doWork() !! fail(error)

Below is what I have implemented using closures.

import Foundation

let throwError = Bool.random()

enum Failure: Error {
    case notWorking

let doWork: () throws -> Void = {
    if throwError {
        throw Failure.notWorking
    print("I'm doing it!")

let fail: (Error) -> Void = { error in
    print("Error: \(error)")

infix operator !!
func !! (work: @autoclosure () -> (() throws -> Void), 
         errorHandler: @autoclosure () -> ((Error) -> Void)) {
    do {
        try work()()
    } catch {

doWork !! fail

This is working but requires closures on order to match the custom operator which is using @autoclosure. Is there syntax which could get closer to the goal of working with 2 expressions?


You may wish to review this thread and the associated proposal:


Thanks, looking.

I've come around to this solution. Attempt or Fail

It defines a couple of functions instead of an operator which is working well enough for my purposes. I determined there would need to be language changes to make the !! operator to work.

Terms of Service

Privacy Policy

Cookie Policy