如何将AnyClass转换为特定的类并在Swift中dynamic初始化?

Object-C中,我将类对象存储在一个数组中,并像这样dynamic地初始化它们:

self.controllers=@[[OneViewController class],[TwoViewController class]]; Class clz = self.controllers[index]; UIViewController *detailViewController = [[clz alloc] init]; 

斯威夫特我尝试这种方式,但它引发了一个错误:

 var controllers:AnyClass[] = [OneViewController.self,TwoViewController.self] var clz : AnyClass = controllers[index] var instance = clz() // Error:'AnyObject' is not constructible with () 

我不知道是否有办法将AnyClass转换为特定的类? 还是其他好主意?

你可以指定数组是通用超类的types,然后键入减法做正确的事情(Beta-3语法):

 let classArray: [UIViewController.Type] = [ OneViewController.self, TwoViewController.self ] let controllerClass = classArray[index] let controller = controllerClass.init() 

我find了解决这个问题的方法:

 var controllers:AnyClass[] = [OneViewController.self,TwoViewController.self] var clz: NSObject.Type = controllers[0] as NSObject.Type var con = clz() 

记得在ViewController的类中添加@objc

一个AnyClassvariables必须先被转换成一个特定的types才能初始化一个实例:

 // Code checked to run on xCode 7.1.1 import UIKit var aClass: AnyClass = UIButton.self // Error: 'init' is a member of the type... // let doesNotWork = aClass.init() // aClass must be casted first var buttonClass = aClass as! UIButton.Type var oneButton = buttonClass!.init() var otherButton = buttonClass!.init(frame: CGRectZero) 

这是一个纯粹的dynamic类types的快速实现。 它确实需要类来扩展相同的协议。

 protocol X{var s:String{get};init(_ s:String)} class A:X{var s:String;required init(_ s:String){self.s = s}} class B:X{var s:String;required init(_ s:String){self.s = s}} var instance:X var classType:X.Type classType = A.self instance = classType.init("abc") print(instance.s)//abc classType = B.self instance = classType.init("123") print(instance.s)//123 

如果这些类都是Objective-C NSObject的子类,那么可以这样做(是的,反引号是有意的):

 var constructors: (Void -> NSObject!)[] = [ NSMutableString.`new`, NSMutableArray.`new`, NSMutableDictionary.`new` ] let string = constructors[0]() (string as NSMutableString).appendString("Hello") let array = constructors[1]() (array as NSMutableArray).addObject("Swift") let dictionary = constructors[2]() (dictionary as NSMutableDictionary).setObject("Objective-C", forKey: "Goodbye") NSLog("dynamically created a string: \(string), an array: \(array), and a dictionary: \(dictionary)") 

它应该输出:

 dynamically created a string: Hello, an array: ( Swift ), and a dictionary: { Goodbye = "Objective-C"; } 

在我看来,应该有一个更优雅的方式来做到这一点。