目前我使用以下代码加载相同nibname的视图控制器
let recommendationVC : RecommendationVC = RecommendationVC(nibName: "RecommendationVC", bundle: nil)
我认为指定nibname是不必要的,因为它与控制器名称相同。因此,我决定使用泛型,并使用泛型推断类型和nib名称。
protocol NibIdentifiable {
static var nibNameIdentifier: String { get }
}
// MARK: - Indentifies each storyboard from its classname.
extension NibIdentifiable where Self: UIViewController {
static var nibNameIdentifier: String {
return String(describing: self)
}
}
extension UIViewController :NibIdentifiable
{
}
extension UIViewController {
func instantiate<Controller: UIViewController>(_: Controller.Type) -> Controller where Controller: NibIdentifiable {
guard let controller = Self(nibName:Controller.nibNameIdentifier,bundle:nil) as? Controller else {
fatalError("Could not dequeue cell with identifier: \(Controller.nibNameIdentifier)")
}
return controller
}
}
但是在尝试创建VC实例时,
let recommendationVC :RecommendationVC = UIViewController.instantiate()
收到错误信息“无法推断出通用参数'Controller'”
这种方法有什么问题吗?
let recommendationVC = RecommendationVC()
即可正常工作。 - dan