Swift Generic Types and Inheritance

62 views Asked by At

I'm creating an app for iOS and I have a function in a view controller called MainVC that has to return another view controller. The view controller that this function has to return inherits from another view controller called FatherVC. My problem is FatherVC has a generic type, and that causes problems...

class MainVC: UIViewController{
    ...

    func returnOtherVC() -> //Here I want to return any class that inherits from FatherVC {
        ...
    }
}

class FatherVC<T : AClass>{
    ...
}

class Child1VC: FatherVC<Class1>{ //Class1 inherits from AClass
    ...
}

class Child2VC: FatherVC<Class2>{ //Class2 inherits from AClass
    ...
}

class Child3VC: FatherVC<Class2>{ //Class3 inherits from AClass
    ...
}

I want returnOtherVC() to return an instance of Child1VC or Child2VC or Child3VC or other classes like these. How can I pull this off?

1

There are 1 answers

0
lorem ipsum On

You are almost there, see the comments.

class MainVC: UIViewController{
    func someInit(){
       //Return any of the children
        let one: Child1VC = returnOtherVC()
        let two: Child2VC = returnOtherVC()
        let three: Child3VC = returnOtherVC()
       //Or the father
        let parent: FatherVC = returnOtherVC()

    }
    func returnOtherVC<FC, AC>() -> FC where FC : FatherVC<AC> {//Here I want to return any class that inherits from FatherVC {
        //Use the required initializer
        return FC()
    }
}
class AClass {}
class FatherVC<T : AClass>{
    //Add a required initilizer so it can be accessed.
    required init(){}
}
//Add inheritance clauses
class Child1VC<Class1>: FatherVC<Class1> where Class1 : AClass{ //Class1 inherits from AClass
}

class Child2VC<Class2>: FatherVC<Class2> where Class2 : AClass{ //Class2 inherits from AClass
}

class Child3VC<Class2>: FatherVC<Class2> where Class2 : AClass{ //Class3 inherits from AClass
}