Call a Swift Singleton from Objective-C

后端 未结 5 623
小蘑菇
小蘑菇 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 00:56

    To make members of the SingletonTest class accessible (swiftSharedInstance is a member of this class), use @objcMembers modifier on the class, or add @objc modifier directly on the swiftSharedInstance:

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

    Or:

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

提交回复
热议问题