Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the initializer of an `open` class need to be open as well?

Swift 3 introduced the new open keyword that I'm using in a framework.

Does an open class in this framework require an open initialiser to be used outside of said framework, or does the init function inherit the open declaration on the class?

For example:

open class OpenClass {
    var A: String

    init() {           // does this init() function need to be marked open?
        A = String()
    }
}

Side question: do the variables in the open class OpenClass inherit the open nature of their class?

like image 362
perhapsmaybeharry Avatar asked Sep 23 '16 01:09

perhapsmaybeharry


People also ask

What does an initializer do in Swift?

An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer.

What is override init in Swift?

Override initializer In Swift initializers are not inherited for subclasses by default. If you want to provide the same initializer for a subclass that the parent class already has, you have to use the override keyword.

What is convenience init Swift?

A convenience initializer is a secondary initializer that must call a designated initializer of the same class. It is useful when you want to provide default values or other custom setup.

What is constructor in Swift?

In Swift, an initializer is a special function that we use to create objects of a particular class, struct, or other type. Initializers are sometimes called constructors, because they “construct” objects.


1 Answers

From SE-0117 Allow distinguishing between public access and public overridability:

Initializers do not participate in open checking; they cannot be declared open, and there are no restrictions on providing an initializer that has the same signature as an initializer in the superclass.

You need not and you cannot declare a init method as open:

open class OpenClass {

    open init() { // error: only classes and overridable class members can be declared 'open'; use 'public'

    }
}

The default access level for all members of a class (properties and methods) is internal, that applies to open classes as well.

like image 173
Martin R Avatar answered Nov 15 '22 08:11

Martin R