迅速-将重新抛出函数另存为非抛出闭包

据我了解,重新抛出本质上是根据单个声明/定义创建两个函数,如下所示:

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() }

如果我有一个像f一样的throwthing函数,是否可以将其保存为“ non-throwing”形式的闭包?假设是这样的:

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
最佳答案
在有人提出更好的解决方案之前:使用包装纸

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

let x: (() -> Void) -> Void = { f($0) }

转载注明原文:迅速-将重新抛出函数另存为非抛出闭包 - 代码日志