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.