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?

5
  • Why is this a generic? What is going to specify T?
    – matt
    May 6, 2015 at 23:53
  • Possible duplicate from here. Might need to change <T> to <T: someProtocol> where the protocol exposes an init() method.
    – gjeck
    May 6, 2015 at 23:58
  • I've checked that question, but seems not correct. May 7, 2015 at 0:00
  • What is selfsender? This is a class method correct?
    – gjeck
    May 7, 2015 at 0:09

1 Answer 1

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.

1
  • Strange grammar with Generic. targetControllerClass seems is externalParameterName in here not localParameterName May 7, 2015 at 0:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.