Creating an object in Swift using the Objective-C factory method gives a compiler error [duplicate]

强颜欢笑 提交于 2019-12-23 16:43:26

问题


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:


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.



来源:https://stackoverflow.com/questions/26491508/creating-an-object-in-swift-using-the-objective-c-factory-method-gives-a-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!