gpt4 book ai didi

swift - 将重新抛出函数保存为非抛出闭包

转载 作者:搜寻专家 更新时间:2023-10-31 22:28:23 24 4
gpt4 key购买 nike

据我所知,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

最佳答案

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

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

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

关于swift - 将重新抛出函数保存为非抛出闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com