Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override generic method in generic class in swift?

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!

like image 212
Yoshikuni Kato Avatar asked Jul 14 '16 12:07

Yoshikuni Kato


1 Answers

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.

like image 63
AnderCover Avatar answered Oct 21 '22 00:10

AnderCover