Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we add designated initialisers in extensions in swift?

The only difference I can see between designated and convenience initialisers is that the former necessarily calls a super class init (if available).

I don't understand then why I can't add a designated init to a class in an extension, while adding a convenience one is OK.

Why is it so bad to have an init from an extension to possibly call a super class initialiser?

like image 728
cfischer Avatar asked Nov 12 '14 00:11

cfischer


People also ask

Which job can Extensions not do in Swift?

Extensions can add new computed properties, but they can't add stored properties, or add property observers to existing properties.

What is designated initializer in Swift?

Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.

How many types of Initializers are there in Swift?

Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. Designated initializers are the primary initializers for a class.

Why do we use extensions in Swift?

Extensions let us add functionality to classes, structs, and more, which is helpful for modifying types we don't own – types that were written by Apple or someone else, for example.


1 Answers

Let's recall what a designated initializer is.

A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.

Excerpt From: 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) {
                ...
        }
}
like image 191
ylin0x81 Avatar answered Oct 09 '22 19:10

ylin0x81