Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an Objective-C class method from Swift language

In my Swift app, I need to access a class method called weibo() as below from Objective-C

@interface Weibo : NSObject
+ (Weibo*)weibo;
@end

I have configured the bridging header and tried the following statement

let w = Weibo.weibo() as Weibo

It doesn't work.

UPDATE: I have forked the repo and fixed this issue as below.

let w = Weibo.getWeibo() as Weibo // the method has been changed.

The reason why it didn't work because Swift treats + (Weibo*)weibo; as a convenience constructor. Since weibo is same as the Class name Weibo although the case is different. I need to change the name to getWeibo to fix this issue to support Swift.

Thanks for every one contributing to this answer. Special thanks to @Anil and @David

Jake

like image 432
Jake Lin Avatar asked Jun 23 '14 13:06

Jake Lin


People also ask

Can we use Swift code in Objective-C?

You can only import "ProductName-Swift. To avoid cyclical references, don't import Swift into an Objective-C header file. Instead, you can forward declare a Swift class to use it in an Objective-C header. Note that you cannot subclass a Swift class in Objective-C.

Can Objective-C class inherit from Swift class?

Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs: You cannot subclass a Swift class in Objective-C.


2 Answers

+ (Weibo*)weibo; is the class method of your class Weibo. You could access it in swift like

let w:Weibo = Weibo.weibo()

But it gives me error when i tried('weibo' is unavailable: use object construction 'Weibo()') may be because of method name and class name are same. When i change the method name error goes

let w:Weibo = Weibo.getWeibo() // works: method name changed
like image 193
Anil Varghese Avatar answered Oct 11 '22 16:10

Anil Varghese


That's a class method not a property.

So you would access it like...

let w = Weibo.weibo()

... I think.

Type would be inferred but you could do it as...

let w:Weibo = Weibo.weibo() as Weibo

I believe, and it would still work.

like image 35
Fogmeister Avatar answered Oct 11 '22 16:10

Fogmeister