在 Swift
中处理可能失败的 init
的最佳方法是什么?例如,您创建了一个依赖于可能不可用的特定资源的类实例。
显然我们有 2 个选择:
- 返回 nil 的 bailable init(Cocoa 方式)
- 抛出错误的 init
见下文
enum ThingError: ErrorType{
case crap
}
class Thing {
init(c: Int) throws{
if c < 0 {
throw ThingError.crap
}
}
}
var c = try Thing(c: 3)
do{
var d = try Thing(c: -4)
}catch{
print("oh vey!")
}
有推荐的方法吗?第二个选项似乎更“敏捷”......
最佳答案
两者都不是天生更好或更快捷。
就我个人而言,我发现 throws
初始化程序非常痛苦。我宁愿让失败的初始化器返回 nil
,因为这样我就可以使用 guard let
进行初始化,而不必在 do/catch< 中包装东西
并处理由此产生的范围问题。您的代码说明了问题;您的 var d
被“卡住”在 do
范围内。我宁愿这样说:
guard let d = Thing(c:-4) else {return}
// now d is unwrapped and in scope!
...比这个(你要说的):
do {
var d = try Thing(c: -4)
} catch {
print("oh vey!")
}
// and here there is no `d`, so _now_ what?
另一方面,抛出错误提供了发送消息的机会,即交流到底出了什么问题。您不能仅使用 init?
初始化程序来做到这一点;它有效或失败,这就是调用者所知道的。
关于swift - Swift 初始化器中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769819/