Ingo Dellwig
Ingo Dellwig

Reputation: 226

How do I instanciate a class (stored in an Array) in Swift?

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.

Upvotes: 0

Views: 97

Answers (1)

rintaro
rintaro

Reputation: 51911

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.

Upvotes: 2

Related Questions