简体   繁体   中英

Pass two different types of object as one function variable

I want to create a function that takes two different subclasses of UIViewController. One is a UITableViewController, and one is a UIViewController (both inherit from UIViewController). In my function, I want to then check which type the ViewControllers are, in order to access their properties in my function. How can I do this, if it is possible? I have tired the following:

internal func myFunction(var controller: UIViewController) {

        if controller is MyController {
            controller = controller as! MyController
        }
        // Get errors saying my MyController properties are not available. Type of UIViewController has no member.
}

If I understand you right, you would like to know which type is your parameter. If so, use this kind of method:

internal func myFunction(controller: UIViewController) {

    if let menu = controller as? MenuController {
        //menu is you MenuCOntroller
    } else if let table = controller as? UITableViewController {
        //table is your UITableViewController
    }

}

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