简体   繁体   中英

Create a generic function that takes in a view controller type as a parameter and returns a custom view controller based on that type

I'm trying to create a generic function that takes in a view controller type as a parameter and returns a custom view controller based on that type.

func setUpInstance<T>(_ viewControllerType: T, toName: String?) -> T where T: UIViewController {

        switch viewControllerType {

            case  is GetInstructionsModalViewController:
               let getInstructionsVC = getViewController(GetInstructionsModalViewController.self, "Instructions", identifier: "GetInstructionsVC")
                     getInstructionsVC.delegate = self
                     getInstructionsVC.getDirectionsDelegate = self
                     getInstructionsVC.modalPresentationStyle = .overCurrentContext
                     moveButtonsAccordingToViewHeight(getInstructionsVC.height)

                 return getInstructionsVC as! T

           case is TurnModalViewController:
                let turnVC = getViewController(TurnModalViewController.self, "Turns", identifier: "TurnVC")
                    turnVC.modalPresentationStyle = .overCurrentContext
                    turnVC.delegate = self
                    turnVC.toName = toName
                    bottomContainer.isHidden = true
                    moveButtonsAccordingToViewHeight(turnVC.height)
               return turnVC as! T

           default:
                return UIViewController.self as! T
            }

        }

when I try and instantiate the custom view controller:

let turnVC = setUpInstance(TurnModalViewController, toName: nil)

I get an error:

Cannot convert value of type 'TurnByTurnModalViewController.Type' to expected argument type 'UIViewController'

Any idea on how to make this function do its job properly?

Looks like you mixed up how to use generics. First of all, you need to change the signature of the function to

func setUpInstance<T>(_ viewControllerType: T.Type, toName: String?) -> T where T: UIViewController

since you'd like to check the input type and return the instance of that type

then call it with the right parameter

let turnVC = setUpInstance(TurnModalViewController.self, toName: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM