4

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)
    }
Thomas Easo
  • 3,457
  • 3
  • 21
  • 32
  • your `popupStoryboardID` and popUpVCType both are assigned in the same name or else, Generics is the good approach for your concept – Anbu.Karthik Feb 03 '18 at 06:28
  • @Anbu.karthik popupStoryboarID is a string which is the storyboardid in UI and popUpVCType is a way to get the type of the PopUpViewController object – Thomas Easo Feb 03 '18 at 07:31

1 Answers1

6

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)
ZeMoon
  • 20,054
  • 5
  • 57
  • 98