gpt4 book ai didi

swift - 在 Swift 中传播参数验证错误的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-28 08:40:58 25 4
gpt4 key购买 nike

在 Swift 中给定参数无效的函数是否有一种标准的方法来传播错误?

我知道我可以自己定义 ErrorType。但如果有标准方法,我想避免重复工作。

另一个选项是使返回类型可为空。(我个人更喜欢抛出错误,因为使用 try? 我们可以获得相同的效果。)

在 Swift 中,什么方式被视为“标准”或“好”?

最佳答案

我用相同的方式告诉使用我的代码的开发人员出了点问题。要准确,因为它会停止应用程序。

class AbstractMethodException: NSException {
init() {
super.init(
name: "Called an abstract method",
reason: "All abstract methods must be overriden by subclasses",
userInfo: nil)
}
//required by Xcode compiler. strange thing
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

还有一个使用示例,说明如何为抽象函数引发异常。

func update(withData data: PVModel) {
AbstractMethodException().raise()
}

如果只需要抛出错误,我建议使用 ErrorType 协议(protocol)。

关于swift - 在 Swift 中传播参数验证错误的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36466895/

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