How to use a generic class without a type argument in Swift?

I want to encapsulate a shared object in another class without setting the generic type argument. I created the base class Animal<T> and defined other subclasses from it. Example:

 public class Animal<T: YummyObject> { // Code } public class Dog: Animal<Bark> { // Code } public class Cat: Animal<Meow> { // Code } 

and defined the Animal property with no type argument in the UITableView extension below:

 extension UITableView { private static var animal: Animal! func addAnimal(animal: Animal) { UITableView.animal = animal } } 

but at the same time I get the following compilation error:

A reference to the generic type Animal requires arguments in <...> .

It seems to work fine in Java . How can I accomplish the same thing in Swift ?

+5
source share
1 answer

Swift does not yet support common wildcard style patterns such as Java (i.e. Animal<?> ). Thus, the general pattern is to define a superclass, protocol (or shell) that is erased by type, to use such use instead. For instance:

 public class AnyAnimal { /* non-generic methods */ } 

and then use it as your superclass:

 public class Animal<T: YummyObject>: AnyAnimal { ... } 

Finally, use AnyAnimal instead of your non-generic code:

 private static var animal: AnyAnimal! 

Examples in the standard Swift library . For a practical example, see KeyPath , PartialKeyPath and AnyKeyPath class hierarchy. They follow the same pattern as I mentioned above. The collection structure provides even more examples of erasing styles, but uses a wrapper instead.

+4
source

Source: https://habr.com/ru/post/1272243/


All Articles