Swift 泛型类型和继承

问题描述 投票:0回答:1

我正在为 iOS 创建一个应用程序,并且我在视图控制器中有一个名为 MainVC 的函数,它必须返回另一个视图控制器。该函数必须返回的视图控制器继承自另一个名为FatherVC 的视图控制器。我的问题是 FatherVC 有一个泛型类型,这会导致问题......

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
    ...
}

我希望 returnOtherVC() 返回 Child1VC 或 Child2VC 或 Child3VC 或其他类似类的实例。我怎样才能做到这一点?

ios swift xcode inheritance viewcontroller
1个回答
0
投票

你就快到了,看看评论。

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
}
© www.soinside.com 2019 - 2024. All rights reserved.