Possible to define a generic class with a generic subclass?

Realize this is probably impossible, but anyway here goes. I was able to create a suite of subclasses in Objective-C by using the preprocessor and including a "generic" interface/implementation using string substitution.

What I'm trying to achieve is a final class that records metrics on usage. All subclasses are UIViewController subclasses, and several methods are overloaded (viewDidLoad, viewDidAppear, etc).

So what I'd dearly love is something like:
class Info<Y: UIViewController> : Y

I'd then have Info<UIViewController>, Info<UITableViewController>, etc.

Figured I'd at least ask here to see if anyone has suggestions. If not I can create a protocol with default methods for everything not related to an overloaded function .

1 Like

No, it's not really possible to create such stand-ins. You could try some shenanigans with Obj-C swizzling, but that's generally a bad idea. I can see why you want such a thing, but it's simple to just create a single subclass of the relevant controllers, integrate your metrics and analytics calls, and then use that as the superclass of all the controllers in your app. Given there are only a few controller types you'd actually want, it's not actually that much code. I usually do just UIViewController and UINavigationController. UITableViewController is fairly useless.

2 Likes

But I have to then copy paste to each? All changes need to be properly made to each subclass. It’s the possibility of humans making errors doing that over time that is troubling.

I’m not sure what you mean. You’d just have to ensure you subclass your custom superclass rather than the UIKit types directly.

I’ll have a subclass for uiviewcontroller, one for uicollectionviewcontroller, then I have some pdfviewersubclass etc. I just did this in objc and used the pre processor to create everything from a “template”. [excuse typos but doing this on an ipad].

I didn’t think it was possible to use generics, but I’m a beginner with that skill, so wanted to be sure I didn’t miss anything.

Working with a big old creaky ObjC app and slowly converting it to Swift.

You can use something like Sourcery to generate the superclasses, like you were with macros, but manually maintaining the few classes you’d need shouldn’t be that much trouble. Like I said, UICollectionViewController and UITableViewController are pretty worthless, so you can save yourself some trouble if you don’t support them. But code generation is really the only alternative to complex macros in Swift.

2 Likes