This question already has an answer here:
-
Create Swift instance from Objective-C factory method
1 answer
I'm trying to initiate a serial connection using ORSSerialport
, an Objective-C serial library. I have already used it successfully to find all serial ports but am having problems opening a connection.
The documentation shows the opening of a port as such:
ORSSerialPort *serialPort = [ORSSerialPort serialPortWithPath:@"/dev/cu.KeySerial1"];
I have written the following:
let serialPort: ORSSerialPort.serialPortWithPath(serialListPullDown.selectedItem)
However, Xcode isn't autocompleting my method and won't compile. Giving me the error "serialPortWithPath is not a member type of ORSSerialport". I have the bridging header set up correctly and I have used another class in the same library already with a similar syntax with no problems. What has happened here?
Short answer: Create the object with
let serialPort = ORSSerialPort(path:"/dev/cu.KeySerial1")
Details: The Objective-C factory method
+ (ORSSerialPort *)serialPortWithPath:(NSString *)devicePath;
is mapped to Swift as
init!(path devicePath: String!) -> ORSSerialPort
This is documented in "Interacting with Objective-C APIs" (thanks to Nate Cook!):
For consistency and simplicity, Objective-C factory methods get mapped
as convenience initializers in Swift. This mapping allows them to be
used with the same concise, clear syntax as initializers.
That means that the factory method is mapped to the same Swift method as the
Objective-C init method
- (id)initWithPath:(NSString *)devicePath;
Both would be called from Swift as
let serialPort = ORSSerialPort(path:"/dev/cu.KeySerial1")
and it turns out that this calls the init method. As a consequence,
the factory method cannot be called from Swift.