How to call factory method of Objective-C class from Swift?

I have an obj-c class that uses the factory method to instantiate itself as a singleton. I added this class to my Swift bridge header and want to call this factory method from the swift class. However, Xcode will not let me.

Obj-c code:

@interface MOAssistant : NSObject { ... + (MOAssistant *)assistant; @end 

Swift Code:

 let assistant = MOAssistant.assistant; 

With this code, I get an error message:

'assistant ()' is not available: use the object construct 'MOAssistant ()'

I read the mapping of factory methods to Swift initializers , but I wonder why I can just use:

 let fm = NSFileManager.defaultManager; 

although defaultManager is also a factory. This confuses. I read other posts here as they are:

but none of them explain why Swift behaves differently. Using the recommended method ( MOAssistant() ) is not a solution, since it directly calls the initializer of this class (which I don't want).

+5
source share
1 answer

How often: explain your problem well, and you can find the answer yourself. This is a naming issue. By renaming the factory method to something else, such as defaultAssistant or something unrelated, for example makeThisInstanceForMe , I can easily access it from Swift. It seems that the creator of the swift header is deleting uppercase letters to see if this matches the function name (case insensitive), and if so, then instead of the class function, it turns into a call to the Swift initializer.

However, keep in mind the factory method call as a method / function (including parentheses), otherwise you will get something else, but not what you expect. If you specify a type, you cannot actually call it.

LLDB output if you do not use parentheses:

(lldb) po assistant

(Pecunia`_TPA__TTOFCSo11MOAssistant8makeThisfMS_FT_GSQS__ at RemoteResourceManager.swift)

This problem is actually another dangerous problem that you get if you use automatic / weak typing. There is a reason why weak languages ​​are considered dangerous, although they are convenient.

+3
source

Source: https://habr.com/ru/post/1205019/


All Articles