简体   繁体   English

为Swift覆盖失败的初始化程序

[英]Overriding a Failable Initializer for Swift

Here is a link to a Swift tutorial. 这是Swift教程的链接 In section Initialization-Overriding a Failable Initializer Note that if you override a failable superclass initializer with a nonfailable subclass initializer, the subclass initializer cannot delegate up to the superclass initializer. 初始化-覆盖失败的初始化器一节中,请注意,如果使用不可失败的子类初始化器覆盖了失败的超类初始化器,则子类初始化器将无法委托给超类初始化器。

But the example below: 但是下面的例子:

class Document {
    var name: String?
    // this initializer creates a document with a nil name value
    init() {}
    // this initializer creates a document with a non-empty name value
    init?(name: String) {
        if name.isEmpty { return nil }
        self.name = name
    }
}

and: 和:

class AutomaticallyNamedDocument: Document {
    override init() {
      super.init()
      self.name = "[Untitled]"
    }
    // This is nonfailable override superclass's failable 
    override init(name: String) {
      // Why subclass initializer still can delegate up to the superclass initializer??
      super.init()
      if name.isEmpty {
        self.name = "[Untitled]"
      } else {
        self.name = name
      }
    }
}

Subclass initializer cannot delegate up to the superclass initializer Why subclass initializer still can delegate up to the superclass initializer? 子类初始化器无法委托给超类初始化器?为什么子类初始化器仍可以委托给超类初始化器?

That passage means that you can't delegate up to the overridden failable initializer . 那段话意味着您不能委托重写的失败的初始化器 Note this earlier passage: 请注意以下较早的段落:

A failable initializer of a class, structure, or enumeration can delegate across to another failable initializer from the same class, structure, or enumeration. 一个类,结构或枚举的失败初始化器可以委托来自同一类,结构或枚举的另一个失败初始化器。 Similarly, a subclass failable initializer can delegate up to a superclass failable initializer. 类似地,子类可故障初始化器可以委托最多超类可故障初始化器。

In either case, if you delegate to another initializer that causes initialization to fail, the entire initialization process fails immediately, and no further initialization code is executed. 在任何一种情况下,如果委托给另一个导致初始化失败的初始化程序,则整个初始化过程将立即失败,并且不会再执行任何初始化代码。

That should make it clear why you can't delegate to the overridden failable initializer - were it actually to fail, the whole initialization process would fail, but you're in the middle of a non failable initializer. 这应该清楚说明为什么您不能委托给被覆盖的可失败初始化器-如果它实际上失败了,整个初始化过程将失败,但是您处于不可失败初始化器的中间。

In your case, you're delegating up to a nonfailable initializer of the superclass ( super.init() ), so there's no problem. 在您的情况下,您要委派给超类的不可失败的初始化程序( super.init() ),因此没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM