Reputation: 3758
Explanation
I am defining a generic API method to handle popup across my application. Is it possible to pass a type of a UIViewController to a function and type cast the variable popOverVC in the function to the type of popUpVC ie., passed to the function as argument. All programs under Swift are appreciable
Reference Code
func showAsPopUp(currentVC: UIViewController,currentVCname: String, popupStoryboardID: String, popUpVC:UIViewController){
let popUpVCType:AnyClass = type(of: popUpVC)
let popOverVC = UIStoryboard(name: currentVCname, bundle: nil).instantiateInitialViewController(popupStoryboardID) as! popUpVCType
currentVC.addChildViewController(popOverVC)
}
Upvotes: 5
Views: 2647
Reputation: 20284
This is a good situation to use generics.
func showAsPopUp<T: UIViewController>(currentVC: UIViewController,currentVCname: String, popupStoryboardID: String, popUpVC: T.type) {
let popOverVC = UIStoryboard(name: currentVCname, bundle: nil).instantiateViewController(withIdentifier: popupStoryboardID) as! T
currentVC.addChildViewController(popOverVC)
}
Not sure what your functionality is here, but this is how the generics would fit in with the above mentioned code.
The usage of the above method would look like:
showAsPopUp(currentVC: UIViewController(), currentVCname: "asdsadv", popupStoryboardID: "asd", popUpVC: SomePopUpViewController.self)
Upvotes: 7