BlackBox BlackBox - 7 months ago 41
Objective-C Question

Implement an Objective-C method with light weight generics in Swift

I have to implement this method in a DataSource protocol of an Objective-C library

(nullable id<SomeClass>)someMethod;

I am trying to implement it in my class in Swift, specifically, the AppDelegate, with what I believe keeps equal the signature

extension AppDelegate: LIBDataSource {
@objc func someMethod<T: SomeClass>() -> T? {
return nil // temporary

The problem is that

  • As it is, I have a warning and an error. The error says
    Method cannot be marked @objc because it has generic parameters
    (the warning below is also shown)

  • If I remove
    , the warning says
    Non-@objc method 'someMethod()' cannot satisfy optional requirement of @objc protocol LIBDataSource

Is there a way to implement a generic Obj-C method of a Obj-C protocol in Swift? Or do I have to do a separate Objective-C class to accomplish this?


The syntax


is nothing to do with lightweight generics, it means "any Objective-C class as long as it conforms the protocol SomeClass". Your method doesn't need to be generic but it does need to return an object that conforms to the SomeClass protocol. It's signature should probably be something like

func someMethod() -> SomeClass?