0

The required modifier is "to indicate that every subclass of the class must implement that initializer" :

class SomeClass {
    required init() {
        // initializer implementation goes here
    }
}

This entails that the subclasses don't have to inherit the superclasses' initializers. In fact, this Stackoverflow answer says that if a subclass has a designated initializer of its own, then it doesn't have to inherit the superclass' initializer.

However, the Swift documentation says that every class has to have a at least one designated initializer that "calls an appropriate superclass initializer to continue the initialization process up the superclass chain."

My questions are:

  1. Can a subclass not inherit the superclass' initializer and, if so, in what cases it is beneficial to not inherit it?
  2. What exactly does the required initializer do and in what case is satisfying the initializer inheritance requirement necessary?
Kevvv
  • 3,655
  • 10
  • 44
  • 90

1 Answers1

1

Try and think about it in terms of what initialization does for an object. It sets values to parameters that do not have values set to them yet that need values set before use. See: https://docs.swift.org/swift-book/LanguageGuide/Initialization.html#ID228. So each class needs to have a way to initialize it and if necessary deal with setting variables or passing that responsibility along the subclass chain. The required init() function should be used as a unique case where somewhere in the initialization chain a special property is computed/set in required init() of a super class that makes it a requirement to call required init() in a subclass/subclasses of it. You do not need to write override required in this case.

Greg Price
  • 2,556
  • 1
  • 24
  • 33
  • Can the same result be achieved by using `super.init()` without the `required` modifier? – Kevvv Jul 23 '20 at 21:01
  • Technically yes, however required makes it mandatory and is useful when the super classes are abstracted away or not visible – Greg Price Jul 23 '20 at 21:32