5

据我了解,rethrows基本上从单个声明/定义中创建了两个函数,如下所示:

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,有没有办法将它保存为“非抛出”形式的闭包?假设,像这样:

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
4

1 回答 1

3

直到有人提出更好的解决方案:使用包装器

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

let x: (() -> Void) -> Void = { f($0) }
于 2017-04-09T07:37:58.753 回答