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

Leave a Comment