My Objective-C framework defines a protocol with a singleton getter:
@protocol ShareableProtocol
+ (nonnull instancetype)sharedInstance;
@endA Swift class implements the protocol.
import SharingFramework
public class ShareableClass: NSObject, ShareableProtocol {
public static singleton = ShareableClass()
public static func sharedInstance() -> Self {
return singleton // error
}
}The sharedInstance signature was generated by Swift 5. How might I return a concrete class instance, singleton, while satisfying the 'Self' return type? The compiler wants a dynamic return type (like Self) in order to also work from inherited classes, but I don't know how to return an explicit object (singleton) in this way. I've tried:
- "return singleton" fails with "Cannot convert return expression of type 'ShareableClass' to return type 'Self'. This is because of SR-695.
- "return singleton as ShareableProtocol" fails similarly: cannot convert type ShareableProtocol to type Self.
- Changing sharedInstance()'s return type to ShareableProtocol or ShareableClass causes the class to no longer conform to ShareableProtocol.
- Making the class final and returning my class type satisfies SR-695 and compiles, but feels forced because I don't necessarily want this class final. I suspect there is a more dynamic way, saying "I'm returning an instance of the current class, whatever that is."
public final class ShareableClass: NSObject, ShareableProtocol { // add 'final'
public static func sharedInstance() -> ShareableClass { // return concrete classThank you.