Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 489
drinking Avatar asked Jun 09 '14 11:06

drinking


2 Answers

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() 
like image 135
DarkDust Avatar answered Oct 07 '22 01:10

DarkDust


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

like image 23
Xianng Avatar answered Oct 07 '22 03:10

Xianng