Creating an object in Swift using the Objective-C

2019-07-05 00:47发布

This question already has an answer here:

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?

1条回答
Fickle 薄情
2楼-- · 2019-07-05 01:39

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.

查看更多
登录 后发表回答