0

I want to define enclosure method,which can goto an view controller like gotopage(currentController,TargetViewController,"targetidentify")

   class func gotoPage<T: UIViewController>(currentController:ViewController,targetControllerClass: T.Type,identify:String){
        var mTargetViewController:targetControllerClass  =  currentController.storyboard?.instantiateViewControllerWithIdentifier(identify) as! targetControllerClass
        currentController.showViewController(mTargetViewController, sender: currentController)
    }

Here is another similar question I have referenced. The question is as! targetControllerClass maybe not correct. and error while building: "targetControllerClass" is not a type. enter image description here How can I define this method with Class Type?

Community
  • 1
  • 1
Albert.Qing
  • 4,220
  • 4
  • 37
  • 49

1 Answers1

2

All view controllers will inherit from UIViewController, given that you can adjust your method as follows:

func gotoPage<T>(currentController: UIViewController, targetControllerClass: T.Type, identify: String) {
    var newController = currentController.storyboard?.instantiateViewControllerWithIdentifier(identify) as! UIViewController
    if newController is T {
        currentController.showViewController(newController, sender: currentController)
    }
}

You can then call it as follows:

gotoPage(self, targetControllerClass: UIPageViewController.self, identify: "test")

However, the addition of generics isn't very beneficial here.

gjeck
  • 313
  • 2
  • 11
  • Strange grammar with Generic. targetControllerClass seems is externalParameterName in here not localParameterName – Albert.Qing May 07 '15 at 00:46