Swift初始化中的错误 [英] Errors in Swift initialisers
问题描述
处理在 Swift
中可能失败的 init
的最佳方法是什么?例如,您创建一个依赖于某个可能不可用的资源的类的实例。
What is the best way to handle an init
that might fail in Swift
? For example, you create an instance of class that depends on a certain resource that might not be available.
显然,我们有两个选项:
Apparently we have 2 options:
- 返回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!")
}
有没有推荐的方法?第二个选项似乎更多的Swifty...
Is there a recommended way of doing this? The second option seems more "Swifty"...
推荐答案
本质上更好或Swiftier。
Neither is inherently better or Swiftier.
我个人觉得 throws
初始化器是一个巨大的痛苦。我更愿意有一个失败的初始化方法返回 nil
,因为然后我可以用 guard let
必须在 do / catch
中包装内容,并处理结果范围问题。你的代码说明了这个问题;您的 var d
在 do
范围内是stuck。我宁愿这样说:
Personally I find throws
initializers a huge pain. I'd much rather have a failed initializer return nil
, because then I can do my initialization with guard let
instead of having to wrap things in do/catch
and deal with the resulting scoping issues. Your code illustrates the problem; your var d
is "stuck" inside a do
scope. I'd rather say this:
guard let d = Thing(c:-4) else {return}
// now d is unwrapped and in scope!
...比这更好
...than this (what you have to say):
do {
var d = try Thing(c: -4)
} catch {
print("oh vey!")
}
// and here there is no `d`, so _now_ what?
另一方面,抛出错误提供了发送消息的机会,即交际关于究竟发生了什么问题。你不能用 init?
初始化器来做到这一点;它工作或它失败,这是所有的调用者知道。
On the other hand, throwing an error offers an opportunity to send a message, i.e. to be communicative about exactly what went wrong. You can't do that with a mere init?
initializer; it works or it fails, and that's all the caller knows.
这篇关于Swift初始化中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!