13

I want to encapsulate a generic object in another class without setting the generic type argument. I created a base Animal<T> class 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 an Animal property, without the type argument, in the UITableView extension bellow:

extension UITableView {
    private static var animal: Animal!

    func addAnimal(animal: Animal) {
        UITableView.animal = animal
    }
}

but I get the following compile error when doing so:

Reference to generic type Animal requires arguments in <...>.

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

3
  • 1
    Can you please show us what is Meow and Bark. Is it a class, or a protocol. Also, what is the reason you want to assign a table to an animal and not some protocol. btw, Car doesn't go meow, it goes beeep beeep Commented Sep 30, 2017 at 5:05
  • 2
    @iWheelBuy It is a dummy object and a class Commented Sep 30, 2017 at 8:41
  • I would question whether this is a generic situation. Unless you show more info to the contrary, this looks like a use case for a protocol, not a generic. Commented Sep 30, 2017 at 15:41

1 Answer 1

13

Swift doesn’t yet support wildcard-style generics like Java does (i.e., Animal<?>). As such, a common pattern is to define a type-erased superclass, protocol (or wrapper) to enable such usage 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 in your non-generic code instead:

private static var animal: AnyAnimal!

Examples in the Swift Standard Library. For a practical example, see the KeyPath, PartialKeyPath, and AnyKeyPath classes hierarchy. They follow the same pattern I outlined above. The Collections framework provides even further type-erasing examples, but using wrappers instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Not applicable if the type you want to erase already extends another class and that class is a generic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.