arithma
arithma

Reputation: 436

Extend a type using generics

In Swift, I am trying to create a generic class that can extend another class, while inheriting from it. I am able to do it in C++ as follows, but is there a way to do the same in Swift?

class Atom {};

template<typename Base, typename Extension>
class Extend: Base {
    Extension _value;
};

int main() {
    return 0;
}

One approach I have been trying to apply is Protocol Oriented Design, but it doesn't seem to be able to take a class and extend it. The best I reached is something like creating the extension manually, and declaring that it does extend Atom, but at that point, I would just create another class and add to it the respective property manually.

Upvotes: 0

Views: 158

Answers (1)

Ahmad sibai
Ahmad sibai

Reputation: 177

One way to do it is by generating the code for the subclass at compile or run time. check these answers of these questions: How to generate code dynamically with annotations at build time in Java?, and Generating, compiling and using Java code at run time?. You can add a custom generic method to the base class that would be overridden by each subclass (in the generated code) and it may return Object. It would be a working approach, if it's worth the hassle.

Upvotes: 2

Related Questions