2

I have seen this question on stackoverflow Here Unfortunately, this answer is not helpful in swift3.x

protocol Effect {

    func des()
}

class A: Effect {

    func des() {
        print("This is A")
    }

    required init() { }
}

class B: Effect {

    func des() {
        print("This is B")
    }

    required init() { }
}

I want to store class A & B in an array

var array = [Effect.Type]()
array.append(A.self)
array.append(B.self)

When I want to get class A & B from array, I get this result

A.self   // __lldb_expr_23.A.Type
A.self.init().des() -> This i A
array[0] // __lldb_expr_23.A.Type
array[0].init().des() -> Error

Error Image

I know I can use this method to init Class A

let a = array[0] as! A.Type
a.init().des() -> This is class A

But if I don't know the class exactly, I cannot init the class by Effect.Type So How to use AnyClass to init an specific class instance without use as! ... in Swift3.x?

Community
  • 1
  • 1
pluto
  • 516
  • 6
  • 9

1 Answers1

2

You have to add init() as requirement to the protocol definition in order to call it on the array values of type Effect.Type:

protocol Effect {
    init()
    func des()
}

Then everything works as expected:

let array: [Effect.Type] = [ A.self, B.self ]

array[0].init().des() // This is A
array[1].init().des() // This is B
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382