Escape hatch for rethrows diagnostic

This probably will be solved by the Typed throws, but for now I need some workaround with existing compiler:

func withoutAnimation<R>(_ body: () throws -> R) rethrows -> R {
    var result: Result<R, Error>?
    UIView.performWithoutAnimation {
        result = Result(catching: body)
    }
    // ERROR: Call can throw, but the error is not handled; a function declared 'rethrows' may only throw if its parameter does
    return try result!.get()
}

One of the possible workarounds would be to create two overloads for this function and all the generic callers - one for throwing case, another for non-throwing. Any better ideas?

Could you inline Result(catching: body) and write the do/catch block explicitly?

This would not help - problem is with get, not with init.

In February 2018, @beccadax pitched to add an affordance into the language and/or standard library to opt out of the rethrows checks, but I don't think that went anywhere at the time: Pitch: `rethrows(unchecked)`

Around the same time, I wrote a blog post that illustrates a possible workaround Brent mentioned: A better NSManagedObjectContext​.performAndWait. Check out the "Outsmarting the type checker" section.

I don't know if this workaround still works or if it's even applicable to your problem, but it might be.

1 Like