swift - How to use AnyClass to init an specific class instance in swift3.x -
i have seen question on stackoverflow here unfortunately, answer not helpful in swift3.x
protocol effect { func des() } class a: effect { func des() { print("this a") } required init() { } } class b: effect { func des() { print("this b") } required init() { } }
i want store class & b in array
var array = [effect.type]() array.append(a.self) array.append(b.self)
when want class & b array, result
a.self // __lldb_expr_23.a.type a.self.init().des() -> array[0] // __lldb_expr_23.a.type array[0].init().des() -> error
i know can use method init class a
let = array[0] as! a.type a.init().des() -> class
but if don't know class exactly, cannot init class effect.type how use anyclass init specific class instance without use as! ... in swift3.x?
you have add init()
requirement protocol definition in order call on array values of type effect.type
:
protocol effect { init() func des() }
then works expected:
let array: [effect.type] = [ a.self, b.self ] array[0].init().des() // array[1].init().des() // b
Comments
Post a Comment