Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limitation with classes derived from generic classes in swift

I'm trying to derive my class from generic class:

class foo<T> {} class bar : foo<Int> {} 

But this code fails to compile with en error:

Classes derived from generic classes must also be generic

How to avoid this limitation? Is it possible?

like image 395
ssgreg Avatar asked Jun 10 '14 10:06

ssgreg


People also ask

What are the advantages of generic class compared to regular class?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Can a generic class be derived from another generic class?

In the same way, you can derive a generic class from another generic class that derived from a generic interface. You may be tempted to derive just any type of class from it. One of the features of generics is that you can create a class that must implement the functionality of a certain abstract class of your choice.

What is difference between class and generic class?

The generic class works with multiple data types. A normal class works with only one kind of data type.

What are the advantages of using generics?

Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced. Better performance.


1 Answers

Ssreg,

Unfortunately this is official:

You can subclass a generic class, but the subclass must also be a generic class.

Let us hope Apple fixes this in a future version.

Meanwhile, let us see this as an opportunity to exploit aggregation instead of subclassing.

NOTE:

As a poor man's version of a solution, one could use typealias:

class foo<T> {} class bar<Int> : foo<Int> {} typealias Bar = bar<Int> 

This way, the rest of the code can be written just as if Apple already fixed the matter.

like image 140
Jean Le Moignan Avatar answered Oct 05 '22 16:10

Jean Le Moignan