如何在swift中覆盖泛型类中的泛型方法?
发布时间:2020-12-14 05:24:29 所属栏目:百科 来源:网络整理
导读:我正在迅速学习. 我想覆盖泛型类中的泛型函数. 当我写override关键字时,发生编译错误. class GenericParentU { func genericFuncT(param: T) { print("parent") }}class AbsoluteChild: GenericParentInt { override func genericFuncT(param: T) { print("c
我正在迅速学习.
我想覆盖泛型类中的泛型函数. 当我写override关键字时,发生编译错误. class GenericParent<U> { func genericFunc<T>(param: T) { print("parent") } } class AbsoluteChild: GenericParent<Int> { override func genericFunc<T>(param: T) { print("child") } // ! Method does not override any method from its superclass (compile error) } 我可以省略override关键字. class GenericParent<U> { func genericFunc<T>(param: T) { print("parent") } } class AbsoluteChild: GenericParent<Int> { func genericFunc<T>(param: T) { print("child") } } var object: GenericParent<Int> object = AbsoluteChild() object.genericFunc(1) // print "parent" not "child" // I can call child's method by casting,but in my developing app,I can't know the type to cast. (object as! AbsoluteChild).genericFunc(1) // print "child" 在这个例子中,我想通过object.genericFunc(1)获得“child”. 我怎么能得到这个?是否有任何解决方法来实现这一目标? 我知道我可以通过施法调用孩子的方法.但在我正在开发的实际应用程序中,我无法知道要播放的类型,因为我想让它变成多态. 我也读了Overriding generic function error in swift帖子,但我无法解决这个问题. 谢谢!
通过将对象声明为GenericParent< Int>你把它作为超类的一个实例.
如果您还不确切知道运行时的类型,可以考虑使用协议而不是通用超类.在协议中,您可以定义所需对象的要求. protocol MyObjectType { func genericFunc<T>(param: T) -> () } class AbsoluteChild: MyObjectType { func genericFunc<T>(param: T) { print("hello world") } } var object: MyObjectType object = AbsoluteChild() object.genericFunc(1)// prints "hello world" 如果您仍然需要一个默认实现,就像在原始超类GenericParent中那样,您可以在协议扩展中执行此操作,如下所示: extension MyObjectType { func genericFunc<T>(param: T) { print("default implementation") } } class AnotherObject: MyObjectType { //... } var object2: MyObjectType object2 = AnotherObject() object2.genericFunc(1)// prints "default implementation" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |