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

Yos*_*ato 8 generics overriding swift

我正在迅速学习.我想覆盖泛型类中的泛型函数.

当我写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)
}
Run Code Online (Sandbox Code Playgroud)

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

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"
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我希望得到"孩子"的结果object.genericFunc(1).(换句话说,我想"覆盖"该方法.)

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

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

我还在swift post中阅读了Overriding泛函函数错误,但我无法解决这个问题.

谢谢!

And*_*ver 1

这个问题在 Swift 5 中得到了解决:

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"
Run Code Online (Sandbox Code Playgroud)

现在触发错误:

覆盖声明需要“override”关键字

和 :

class AbsoluteChild: GenericParent<Int> {
    override func genericFunc<T>(_ param: T) { print("child") }
}
Run Code Online (Sandbox Code Playgroud)

该代码两次都会编译并打印 child 。