在Object-C中,我将Class对象存储在数组中,并按如下方式动态初始化:
self.controllers=@[[OneViewController class],[TwoViewController class]]; Class clz = self.controllers[index]; UIViewController *detailViewController = [[clz alloc] init];
在Swift我尝试这种方式,但它引发一个错误:
var controllers:AnyClass[] = [OneViewController.self,TwoViewController.self] var clz : AnyClass = controllers[index] var instance = clz() // Error:'AnyObject' is not constructible with ()
我不知道是否有一种方法来将AnyClass转换为特定的类?
还是任何其他好的想法?
你可以指定数组为普通超类的类型,然后类型deduction做正确的事情(Beta-3语法):
let classArray: [UIViewController.Type] = [ OneViewController.self,TwoViewController.self ] let controllerClass = classArray[index] let controller = controllerClass()