Using a generic Swift class in Objective-C
Swift generic types cannot be used in Objective-C.
This excludes Swift-only features such as those listed here:
- Generics
- ...
There is a workaround for some situations, when you need to import Swift generic class into Objective-C.
Let's say you have Swift REST service, which uses Generics. I'm using Moya
framework and that's how my service looks like:
class AuthService: BaseService<AuthAPI> { func register(email: String) { // ... } }
It's inherited from base service using generics, so I can not use it directly in my Objective-C code.
So here is a workaround:
Lets create AuthServiceProtocol
:
@objc protocol AuthServiceProtocol { func register(email: String)}
Then let's create a factory for service (or a singleton method, no difference):
@objc class Services: NSObject { static let authService: AuthServiceProtocol = AuthService()}
Then I'm able to call my generic Swift auth service from Objective-C code:
- (void)someObjcMethod { [Services.authService registerWithEmail:self.email];}