How can I make input data in func as? ViewController
?
private func toVC<T>(_ id: String, vc: T.Type) {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: id) as? T {
if let window = self.window, let rootVC = window.rootViewController {
var currVC = rootVC
let navVC = UINavigationController()
while let presentVC = currVC.presentedViewController {
currVC = presentVC
}
navVC.viewControllers = [vc]
currVC.present(navVC, animated: true, completion: nil)
}
}
}
I get error Cannot convert value of type 'T' to expected element type 'UIViewController'
in navVC.viewControllers = [vc]
.
How to right create func?
UPD
Change method signature as below specifying T
of type UIViewController
,
private func toVC<T: UIViewController>(_ id: String, vc: T.Type) {
To pass data
for specific controller,
private func toVC<T>(_ id: String, vc: T.Type, data: Any) {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: id) as? T {
if let window = self.window, let rootVC = window.rootViewController {
var currVC = rootVC
let navVC = UINavigationController()
while let presentVC = currVC.presentedViewController {
currVC = presentVC
}
(vc as? MyViewController1)?.data = data
(vc as? MyViewController2)?.data = data
navVC.viewControllers = [vc]
currVC.present(navVC, animated: true, completion: nil)
}
}
}