小编典典

从Objective-C调用Swift Singleton

swift

我无法从Objective-C访问Swift Singleton。

@objc class SingletonTest: NSObject {

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

swiftSharedInstance无法访问。


阅读 427

收藏
2020-07-07

共1个答案

小编典典

现在,我有以下解决方案。也许我忽略了一些使我能够直接访问“ swiftSharedInstance”的东西?

@objc class SingletonTest: NSObject {

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

    // the sharedInstance class method can be reached from ObjC
    class func sharedInstance() -> SingletonTest {
        return SingletonTest.swiftSharedInstance
    }

    // Some testing
    func testTheSingleton() -> String {
        return "Hello World"
    }

}

然后在ObjC中,我可以获取sharedInstance类方法(在导入xcode生成的swift标头绑定之后)

SingletonTest *aTest = [SingletonTest sharedInstance];
NSLog(@"Singleton says: %@", [aTest testTheSingleton]);
2020-07-07