如何在func中将类类型定义为param?

时间:2015-05-06 23:48:36

标签: ios swift generics

我想定义一个可以转到视图控制器的enclosure方法 喜欢    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是我引用的另一个类似问题。 问题是 as! targetControllerClass 可能不正确。 构建时出错:“targetControllerClass”不是类型。 enter image description here 如何使用类类型定义此方法?

1 个答案:

答案 0 :(得分:2)

所有视图控制器都将继承UIViewController,因为您可以按如下方式调整方法:

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

然后您可以按如下方式调用它:

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

然而,添加仿制药在这里并不是非常有益。

相关问题