Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Swift Singleton from Objective-C

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

@objc class SingletonTest: NSObject {

    // swiftSharedInstance is not accessible from ObjC
    class var swiftSharedInstance: SingletonTest {
    struct Singleton {
        static let instance = SingletonTest()
        }
        return Singleton.instance
    }        
}

swiftSharedInstance can not be reached.

like image 574
ekinsol Avatar asked Jun 30 '14 11:06

ekinsol


People also ask

How do I access swift Singleton from Objective C?

To use Swift classes in Obj-C you both need to #import "SingletonTest-Swift. h the generated header or forward declaration with @class MySwiftClass . Additionally the class needs to inherit from an Obj-C class like you have don here with NSObject or be marked with @objc to expose it.

Can singleton class be inherited Swift?

A programmer cannot inherit the pure-singleton class. When you try to inherit any class in swift, you must call the constructor of the superclass.

What is singleton class in Objective C?

What is a Singleton Class? A singleton class returns the same instance no matter how many times an application requests it. Unlike a regular class, A singleton object provides a global point of access to the resources of its class.

What is singleton object in Swift?

In Swift, Singleton is a design pattern that ensures a class can have only one object. Such a class is called singleton class. To create a singleton class, we need to follow some rule. 1. Create a private initializer.


2 Answers

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);
like image 76
rohan-patel Avatar answered Sep 27 '22 22:09

rohan-patel


Swift 5 and above

final class Singleton: NSObject {

    @objc static let shared = Singleton()

    @objc var string: String = "Hello World"

    private override init() {}   
}

use in Objective-C

NSLog("Singleton String = %@", [Singleton shared].string]);
like image 32
Suhit Patil Avatar answered Sep 27 '22 21:09

Suhit Patil