Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use swift class in objective c (not an instance of the class)

All tutorials for using swift code in a primarily objective-c app goes through this process mentioned in this Apple document https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

But this methodology of importing a xyzProjectName-swift.h file and then using

MySwiftClass *swiftObject = [[MySwiftClass alloc] init];
[swiftObject swiftMethod];

required me to create an instance of that swift class. Is it possible to directly access the class itself like [MySwiftClass swiftMethod];

I have not been able to do this until now. Do I have to change my swift code in a certain way to achieve this?

like image 434
Ishaan Sejwal Avatar asked Dec 02 '25 00:12

Ishaan Sejwal


1 Answers

Just tried the following:

class MySwiftClass: NSObject {
    static func swiftMethod() -> String {
        return "hello"
    }
}

And in Objective-C:

NSLog(@"Received from Swift: %@", [MySwiftClass swiftMethod]);

Works for me - are you sure your swiftMethod is static, and not private? You could also try adding @objc in front of the static func – if nothing else, at least it might warn you if there is a reason it can't be accessed from Objective-C.

like image 70
Arkku Avatar answered Dec 03 '25 17:12

Arkku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!