What are convenience required initializers in Swift?

后端 未结 3 935
天涯浪人
天涯浪人 2020-12-31 05:11

I saw in this answer that the user specifies a convenience required init(). What exactly does this mean?

I understand that the required key

3条回答
  •  -上瘾入骨i
    2020-12-31 06:15

    A convenience required initializer is an initializer that is enforced onto all subclasses but is not the designated initializer. This means that said initializer will eventually call a designated initializer in its initialization chain.

    Designated Initialisers

    A designated initialiser is the canonical initializer for a class and the one which all required and convenience initialisers should call. The Docs say:

    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.

    Convenience Initialisers

    A convenience initialiser is an initializer that sets up certain configuration information on a class...conveniently. Documentation:

    Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type.

    You do not have to provide convenience initializers if your class does not require them. Create convenience initializers whenever a shortcut to a common initialization pattern will save time or make initialization of the class clearer in intent

    Required Initialisers

    Required initializers can be thought of as a binding contract between a parents interface and subsequent subclasses. Its your means of enforcing that all your children are aware of and implement a certain set of initialisers.

    Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer:

提交回复
热议问题