I'm learning swift. I want to override generic function in generic class.
When I write override
keyword, compile error happens.
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)
}
I can omit override
keyword.
But when I declare the object type as "Parent", the parent's method is called (not the child method). It's not "overriding" literally.
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"
In this example, I want to get "child" as a result of object.genericFunc(1)
.
(In other words, I want to "override" the method.)
How can I get this? Are there any workarounds to achieve this?
I know that I can call child's method by casting. But in the actual app I'm developing, I can't know the type to cast because I want to make it polymorphic.
I also read Overriding generic function error in swift post, but I couldn't solve this problem.
Thank you!
This issue is resolved in 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"
now triggers an error :
Overriding declaration requires an 'override' keyword
with :
class AbsoluteChild: GenericParent<Int> {
override func genericFunc<T>(_ param: T) { print("child") }
}
the code compiles and prints child both time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With