为什么我们不能在swift中添加指定的初始化程序?

时间:2014-11-12 00:44:29

标签: swift initialization

我可以在指定和便利初始化程序之间看到的唯一区别是前者必须调用超类init(如果可用)。

我不明白为什么我不能将指定的init添加到扩展中的类中,而添加一个方便的就是OK。

为什么从扩展程序中获取init可能会调用超类初始化程序这么糟糕?

1 个答案:

答案 0 :(得分:19)

让我们回顾一下指定的初始值设定项。

  

指定的初始值设定项完全初始化所有属性   由该类引入并调用适当的超类   初始化程序继续初始化过程的超类   链

摘自:Apple Inc. “The Swift Programming Language.”

class ClassA {
        private let propertyA: Int

        init(propertyA: Int) {
                self.propertyA = propertyA
        }
}

class ClassB: ClassA {
        private let propertyB: Int

        init(propertyA: Int, propertyB: Int) {
                self.propertyB = propertyB
                super.init(propertyA: propertyA)
        }
}

extension ClassB {
        // If this was a designated initializer, you need to initialize propertyB before calling a superclass initializer.
        // But propertyB is a private property that you can't access.
        // If you don't have the source code of ClassB, you will not even know there is a property called propertyB.
        // This is why we can't use extensions to add designated initializers.
        init(propertyC: Int) {
                ...
        }
}