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.
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.
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 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.
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.
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);
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With