在Swift中传播Argument Validation Error的最佳方法是什么?

时间:2016-04-07 04:45:18

标签: swift error-handling api-design

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

我知道我可以自己定义ErrorType。但如果采用标准方式,我希望避免重复工作。

另一个选项是make return type nullable。 (我个人更喜欢抛出错误,因为尝试?我们可以得到同样的效果。)

什么方式被认为是标准'或者' Good'在斯威夫特?

1 个答案:

答案 0 :(得分:0)

我已经用同样的方法告诉使用我的代码的开发人员出了什么问题。准确,因为它会停止应用程序。

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协议。

相关问题