Call a Swift Singleton from Objective-C

后端 未结 5 624
小蘑菇
小蘑菇 2020-12-06 00:18

I\'m having some trouble accessing a Swift Singleton from Objective-C.

@objc class SingletonTest: NSObject {

    // swiftSharedInstance is not accessible fr         


        
5条回答
  •  星月不相逢
    2020-12-06 01:07

    Nicky Goethlis's answer is correct but I just want to add another way of Singleton creation termed as One line Singleton" in Swift which I came across recently and it does not use Struct:

    Singleton.swift

    @objc class Singleton: NSObject {
    
      static let _singletonInstance = Singleton()
      private override init() {
        //This prevents others from using the default '()' initializer for this class.
      }
    
      // the sharedInstance class method can be reached from ObjC. (From OP's answer.)
      class func sharedInstance() -> Singleton {
        return Singleton._singletonInstance
      }
    
      // Some testing
      func testTheSingleton() -> String {
        return "Hello World"
      }
    }
    

    SomeObjCFile.m

    Singleton *singleton = [Singleton sharedInstance];
    NSString *testing = [singleton testTheSingleton];
    NSLog(@"Testing---> %@",testing);
    

提交回复
热议问题