Extending Obj-C class with lightweight generics in Swift

I am attempting to take a parameterized async stream-like class in Obj-C and write a Swift extension to expose an RxSwift Observable out of it.

@interface TestGenericClass<DataType> : NSObject
- (void)observeWithCallback:(void (^)(DataType data))callback;
@end

The Obj-C generics successfully bridge into Swift:

// compiles :)
let obj = TestGenericClass<NSString>()
obj.observe { (str: NSString) in
    print(str)
}

When I write the Swift extension, however, I get an error about accessing generic parameters at runtime. I don't think my code requires any such runtime access. Is this a compiler wish-list, am I doing something which legitimately cannot be done, or a bug? Any workarounds?

import RxSwift 

// ERROR: Extension of a generic Objective-C class cannot access the class's generic parameters at runtime :(
extension TestGenericClass {
    
    func asObservable() -> Observable<DataType> {

        self.observe { (data: DataType) in
            // publish to an internal Rx.subject
        }

        // return RX.subject.asObservable
    }
}
3 Likes

Same issue. Wondering if there's any solution here...

Same issue, here is what I was doing:

open class NSFetchedResultsController<ResultType> : NSObject where ResultType : NSFetchRequestResult {
}

extension NSFetchedResultsController{
    func existingObject(with objectID: NSManagedObjectID) throws -> [ResultType]?{
        return nil // testing
    }
}

The reason is to solve this problem where I didn't want to mention Event which is used by the
NSFetchedResultsController<Event> so I could reuse this snipped in other files.

I came across this problem again the other day and managed to fix it by casting the fetchedResultsController back to NSFetchedResultsController<NSFetchRequestResult>

The problem only occurs for extensions funcs that are not marked @objc which of course means no Swift types.