Swift初始化程序中的错误

cfi*_*her 3 cocoa swift swift2

处理init可能失败的最佳方法是什么Swift?例如,您创建一个依赖于某个可能不可用的资源的类实例.

显然我们有两个选择:

  • 一个返回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!")
}
Run Code Online (Sandbox Code Playgroud)

有推荐的方法吗?第二种选择似乎更"狡猾"......

mat*_*att 6

既不是天生更好也不是更快.

我个人认为throws初始化者是一个巨大的痛苦.我更倾向于初始化程序返回失败nil,因为那时我可以进行初始化guard let而不必包装内容do/catch并处理生成的作用域问题.您的代码说明了问题; 你var d被困在一个do范围内.我宁愿这样说:

guard let d = Thing(c:-4) else {return}
// now d is unwrapped and in scope!
Run Code Online (Sandbox Code Playgroud)

......比这个(你要说的):

do {
    var d = try Thing(c: -4)
} catch {
    print("oh vey!")
}
// and here there is no `d`, so _now_ what?
Run Code Online (Sandbox Code Playgroud)

在另一方面,抛出一个错误提供了一个机会来发送消息,即是交际究竟哪里出了问题.你不能用纯粹的init?初始化器来做到这一点; 它工作或失败,这是所有来电者都知道的.