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 {
errorHandler()(error)
}
}
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?