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

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


An AnyClass variable must first be casted into a specific type in order to initialize an instance:

// 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)

Here is a pure swift implementation of dynamic class types. It does require the classes to extend the same protocol.

protocol ILayout{ init(_ a:String)}   
class A:ILayout{required init(_ a:String)}  
class B:ILayout{required init(_ a:String)}   
var instance:ILayout   
var classType:ILayout.Type

classType = A.self   
instance = classType.init("abc")

classType = B.self   
instance = classType.init("abc")