Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 491
Mike Lischke Avatar asked Sep 29 '22 14:09

Mike Lischke


1 Answers

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.

like image 191
Mike Lischke Avatar answered Oct 16 '22 19:10

Mike Lischke