Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save rethrowing function as a non-throwing closure

As far as I understand, rethrows essentially creates two functions from a single declaration/definition, like so:

func f(_ c: () throws -> Void) rethrows { try c()}

// has the same effect as declaring two seperate functions, with the same name:

func g(_ c: () throws -> Void) throws { try c() }
func g(_ c: () -> Void) { c() }

If I have a rethrowing function, like f, is there way to save it as a closure in it's "non-throwing" form? Hypothetically, like so:

let x: (() -> Void) -> Void = f
// invalid conversion from throwing function of type '(() throws -> Void) throws -> ()' to non-throwing function type '(() -> Void) -> Void'

x{ print("test") } // "try" not necessary, because x can't throw
like image 490
Alexander Avatar asked Oct 17 '22 14:10

Alexander


1 Answers

Until someone comes up with a better solution: Use a wrapper

func f(_ c: () throws -> Void) rethrows { try c() }

let x: (() -> Void) -> Void = { f($0) }
like image 51
Martin R Avatar answered Oct 21 '22 06:10

Martin R