drinking drinking -4 years ago 125
Swift Question

How to convert AnyClass to a specific Class and init it dynamically in Swift?

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?

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download