I have an obj-c class that uses a factory method to instantiate itself as a singleton. I added that class to my Swift bridge header and want to call this factory method from a swift class. However, XCode won't let me.
The obj-c code is:
@interface MOAssistant : NSObject {
...
+ (MOAssistant *)assistant;
@end
The Swift code is:
let assistant = MOAssistant.assistant;
With this code I get the error:
'assistant()' is unavailable: use object construction 'MOAssistant()'
I read about mapping factory methods to Swift initializers but I wonder why I simply can use:
let fm = NSFileManager.defaultManager;
even though defaultManager is also a factory method. This is confusing. I read other postings here on SO like these:
but none of them explain why Swift behaves differently. Using the recommended way (MOAssistant()
) is no solution as it directly calls the initializer of that class (what I don't want).
As so often: explain your problem well and you may find an answer yourself. It's a matter of naming. By renaming the factory method to something else like defaultAssistant or something unrelated like makeThisInstanceForMe I can easily access it from Swift. Looks like the swift header creator removes the uppercase letters to see if that is the same as the function name (not case sensitive) and if that is the case makes it into a Swift initializer call instead of a class function.
However, keep in mind to call the factory method as method/function (including the parentheses) otherwise you get something else, but not what you expect. If you specify a type you can actually not call it without.
LLDB output when you don't use parentheses:
(lldb) po assistant
(Pecunia`_TPA__TTOFCSo11MOAssistant8makeThisfMS_FT_GSQS__ at RemoteResourceManager.swift)
This problem actually unveils another dangerous problem which you get if you use automatic/weak typing. There's a reason why weakly type languages are considered dangerous, even though they are convenient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With