我有一个 Storyboard和 View Controller 。每个 View Controller 的 Storyboard Id 与分配给它的类名相同。比如:一个漫游 View Controller 被分配了 WalkThroughVC 类,它的 Storyboard Id 也是 WalkThroughVC。
我在下面做了一个函数,从 Storyboard中获取 View Controller 的实例:
func getViewController<T: UIViewController>() -> T? {
let sb = UIStoryboard(name: "Main", bundle: nil)
sb.instantiateViewControllerWithIdentifier(viewController.rawValue) as? T
}
是否可以推断出 T 的类型?如果是,如何?
最佳答案
我想这就是你要找的。p>
class ViewControllers
{
class func getViewController<T : UIViewController>(fromStoryboard : String, fromClass : T) -> T?
{
let storyboard = UIStoryboard(name: fromStoryboard, bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("\(fromClass)") as? T
return controller
}
}
关于ios - 从函数的返回类型推断类型为泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38096417/