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

cfi*_*her 10 initialization swift

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

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

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

yli*_*x81 21

让我们回想一下指定的初始化程序是什么.

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

摘录自:Apple Inc."Swift编程语言".

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) {
                ...
        }
}
Run Code Online (Sandbox Code Playgroud)