如何在swift中覆盖泛型类中的泛型方法?

前端之家收集整理的这篇文章主要介绍了如何在swift中覆盖泛型类中的泛型方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在迅速学习.
我想覆盖泛型类中的泛型函数.

当我写override关键字时,发生编译错误.

  1. class GenericParent<U> {
  2. func genericFunc<T>(param: T) { print("parent") }
  3. }
  4.  
  5. class AbsoluteChild: GenericParent<Int> {
  6. override func genericFunc<T>(param: T) { print("child") }
  7. // ! Method does not override any method from its superclass (compile error)
  8. }

我可以省略override关键字.
但是当我将对象类型声明为“Parent”时,将调用方法(而不是子方法).从字面上看,它并非“压倒一切”.

  1. class GenericParent<U> {
  2. func genericFunc<T>(param: T) { print("parent") }
  3. }
  4.  
  5. class AbsoluteChild: GenericParent<Int> {
  6. func genericFunc<T>(param: T) { print("child") }
  7. }
  8.  
  9. var object: GenericParent<Int>
  10. object = AbsoluteChild()
  11. object.genericFunc(1) // print "parent" not "child"
  12.  
  13. // I can call child's method by casting,but in my developing app,I can't know the type to cast.
  14. (object as! AbsoluteChild).genericFunc(1) // print "child"

在这个例子中,我想通过object.genericFunc(1)获得“child”.
(换句话说,我想“覆盖”该方法.)

我怎么能得到这个?是否有任何解决方法来实现这一目标?

我知道我可以通过施法调用孩子的方法.但在我正在开发的实际应用程序中,我无法知道要播放的类型,因为我想让它变成多态.

我也读了Overriding generic function error in swift帖子,但我无法解决这个问题.

谢谢!

通过将对象声明为GenericParent< Int>你把它作为超类的一个实例.

如果您还不确切知道运行时的类型,可以考虑使用协议而不是通用超类.在协议中,您可以定义所需对象的要求.

  1. protocol MyObjectType {
  2. func genericFunc<T>(param: T) -> ()
  3. }
  4.  
  5. class AbsoluteChild: MyObjectType {
  6. func genericFunc<T>(param: T) {
  7. print("hello world")
  8. }
  9. }
  10.  
  11. var object: MyObjectType
  12. object = AbsoluteChild()
  13. object.genericFunc(1)// prints "hello world"

如果您仍然需要一个默认实现,就像在原始超类GenericParent中那样,您可以在协议扩展中执行此操作,如下所示:

  1. extension MyObjectType {
  2. func genericFunc<T>(param: T) {
  3. print("default implementation")
  4. }
  5. }
  6.  
  7. class AnotherObject: MyObjectType {
  8. //...
  9. }
  10.  
  11. var object2: MyObjectType
  12. object2 = AnotherObject()
  13. object2.genericFunc(1)// prints "default implementation"

猜你在找的Swift相关文章