0

I want to keep an Array of several classes and instanciate them on demand. Here is some demo code:

class AClass {
   func areYouThere() -> String {
      return "Yes, I am!"
   }
}

class FirstClass: AClass {
   override func areYouThere() -> String {
      return "Yes, I am #1!"
   }
}

class SecondClass: AClass {
   override func areYouThere() -> String {
      return "Yes, I am #2!"
   }
}

let className = FirstClass.self
let classReferences: [AClass.Type] = [FirstClass.self, SecondClass.self]

let instanceOfClass = classReferences[0].init()
let test = instanceOfClass.areYouThere()

The code does compile, but when I run it, "test" will keep "Yes, I am!" (without #1), because instanceOfClass is an instance of "AClass", not "FirstClass". I guess, the type [AClass.Type] of my Array is wrong. I also tried "AnyClass", but than the compiler complains, that "init" is not defined in "AnyClass". Any ideas?

Thanks! Ingo.

1 Answer 1

2

You need required init() initializer in your base class.

class AClass {
    required init() {} // <- HERE

    func areYouThere() -> String {
        return "Yes, I am!"
    }
}

Because subclasses may not inherit init() initializer.

IMO, this is a compiler bug. The compiler should report classReferences[0] may not have init().

BTW, you can just:

let instanceOfClass = classReferences[0]()

No need to write .init.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.