Sushil Sharma Sushil Sharma - 3 years ago 135
Objective-C Question

Accessing Swift Class Public Variable in Objective-C Class Xcode 9

I am trying to access Public variable in Objective-C class declared in swift class. But I am getting "Unknown Method" error. Here is my code for accessing variable:

NSLog(@"job on quick blox : %@",[QuickBloxJobClass jobOnQB]);

and it shows compile error:

No known class method for selector 'jobOnQB'

And here is my code in QuickBloxJobClass:

@objc public class QuickBloxJobClass: NSObject
static var jobOnQB: QBCOCustomObject = QBCOCustomObject ()

I cannot make it public variable because I have Class methods in
. Even I tried it by creating a variable for
. But the variable was still unaccessible.
It was working working fine in Xcode .

Please suggest me some solution.

Answer Source

I'm not sure why jobOnQB cannot be public, presence of class methods should not interfere with it being public, but if it cannot be public for some reason, you can add a static method to QuickBloxJobClass to get the variable.

BTW, the syntax [QuickBloxJobClass jobOnQB] is for calling a static method jobOnQB on class QuickBloxJobClass (it works, though). Strictly speaking, however, since jobOnQB is a property, a better Objective-C syntax would be QuickBloxJobClass.jobOnQB.

Another observation is that @objc inference is deprecated in Swift 4, so it's a good idea to explicitly mark Swift methods and properties callable from Swift with @objc. In fact, you have to do it if Swift 3 @objc inference is set to Off.

Update: This needs to be further investigated, it may be just a matter of some settings. I get the behavior you described if I add Swift code to a project initially set up as Objective-C, but internal members defined in Swift can be accessed just fine in Objective-C if the project is initially set up in Swift with Objective-C files added later. Again, if Swift 3 @objc inference is disabled, you still have to mark such members with @objc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download