Returning Self from a non-final class method

My Objective-C framework defines a protocol with a singleton getter:

@protocol ShareableProtocol
+ (nonnull instancetype)sharedInstance;
@end


A 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 class


Thank you.

Seems you know very well about the current limitation of `Self` in Swift, and how to workaround in some limited condition.


Maybe you should better join the dicussion about how Swift should be in the future, better visit forums.swift.org .

Did you read this, as for Swift 5.1 evolutio:n

h ttps://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md


Introduction

Within a class scope,

Self
means "the dynamic class of
self
". This proposal extends that courtesy to value types and to the bodies of class members by renaming
dynamicType
to
Self
. This establishes a universal and consistent way to refer to the dynamic type of the current receiver.

This proposal was discussed on the Swift Evolution list in the [Pitch] Adding a Self type name shortcut for static member access thread.

Returning Self from a non-final class method
 
 
Q