gpt4 book ai didi

swift - 从没有 throws 的继承函数中抛出异常

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

我正在尝试执行以下操作:

protocol X{
func foo()
}
enum XError{
case BAR
}
class Y:X{
func foo(){
throw XError.BAR
}
}

我无法向协议(protocol)添加 throws 声明,它会提示

the error is not handled because the enclosing function is not declared 'throws'.

我怎样才能做到这一点?

最佳答案

您需要在任何抛出的函数的签名中显式添加 throw。

所以

func foo() throws {
throw XError.BAR
}

这也适用于协议(protocol)定义。

protocol X {
func foo() throws
}

Swift 中的错误应该符合 Error 协议(protocol)。

enum XError: Error {
case BAR
}

关于swift - 从没有 throws 的继承函数中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35683128/

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