我学得很快。 我想覆盖泛型类中的泛型函数。
当我写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
关键字。
但是当我将对象类型声明为“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"
在这个例子中,我想得到“child”作为 object.genericFunc(1)
的结果。
(换句话说,我想“覆盖”该方法。)
我怎样才能得到这个?是否有任何解决方法可以实现这一目标?
我知道我可以通过转换调用子方法。但是在我正在开发的实际应用程序中,我不知道要转换的类型,因为我想让它多态。
我还读了Overriding generic function error in swift发布,但我无法解决这个问题。
谢谢!
最佳答案
这个问题在 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"
现在触发错误:
Overriding declaration requires an 'override' keyword
与:
class AbsoluteChild: GenericParent<Int> {
override func genericFunc<T>(_ param: T) { print("child") }
}
代码编译并打印 child 两次。
关于swift - 如何快速覆盖泛型类中的泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38373822/