In Object-C I store Class objects in an array and init them dynamically like this:
self.controllers=@[[OneViewController class],[TwoViewController class]]; Class clz = self.controllers[index]; UIViewController *detailViewController = [[clz alloc] init];
In Swift i try this way but it raises an error:
var controllers:AnyClass[] = [OneViewController.self,TwoViewController.self] var clz : AnyClass = controllers[index] var instance = clz() // Error:'AnyObject' is not constructible with ()
I wonder Whether there is a way to convert AnyClass to a specific Class? Or any other good ideas?
You can specify the array to be of the common superclass' type, then type deduction does the right thing (Beta-3 syntax):
let classArray: [UIViewController.Type] = [ OneViewController.self, TwoViewController.self ] let controllerClass = classArray[index] let controller = controllerClass.init()
i have found a way to solve this problem:
var controllers:AnyClass[] = [OneViewController.self,TwoViewController.self] var clz: NSObject.Type = controllers[0] as NSObject.Type var con = clz()
remember to add @objc in the class of ViewController
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With