I have a legacy Objc class using light-weight generics:
@interface GenericObjcClass <T> : NSObject
- (void)addObserver:(id)obsv callback:(void (^)(T arg))callback;
- (void)postData:(T)data;
@end
@property (nonatomic) GenericObjcClass<NSString *> *testProp;
which I bridge into a modern Swift class while maintaining the generics:
extension Observable {
public static func observable<T>(with: GenericObjcClass<T>) -> Observable<T> where T: AnyObject {
...
}
}
This is great! However, the compiler won't allow me to add nullability to the Objc generic param. Specifically, this is an error:
@property (nonatomic) GenericObjcClass<NSString * _Nullable> *testProp;
// ERROR: `Type argument 'NSString *' cannot explicitly specify nullability`
Since both Obj-C generics and nullability are just compile-time constructs, it seems there should be no issue with these two interacting together. My current workaround is to expose a wrapper class around an optional that can be used when needed:
@interface Optional <T>: NSObject
@property (nonatomic, nullable) T value;
@end
But this means the caller of postData:
has to wrap its parameter, and that I have to create a second Swift Observable extension method just for this wrapper class:
extension Observable {
public static func observable<T>(with: GenericObjcClass<Optional<T>>) -> Observable<T?> where T: AnyObject {
...
}
}
Asking here because I believe Obj-C generics were added to aid in Swift development. Not sure if there's some solution I'm skipping over, but I believe this might be an unnecessary limitation of the Obj-c generics that should be lifted.