使用Objective-C工厂方法在Swift中创建对象会产生编译器错误 [英] Creating an object in Swift using the Objective-C factory method gives a compiler error

查看:144
本文介绍了使用Objective-C工厂方法在Swift中创建对象会产生编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 ORSSerialport (一个Objective-C串行库)启动串行连接。我已经使用它成功找到所有串行端口,但打开一个连接有问题。

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"];

我写了以下内容:

let serialPort: ORSSerialPort.serialPortWithPath(serialListPullDown.selectedItem)

,Xcode不是自动完成我的方法,将不会编译。给我的错误serialPortWithPath不是ORSSerialport的成员类型。我有正确设置的桥接头,我已经使用另一个类在同一库已经有类似的语法没有问题。

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?

推荐答案

简短答案:使用

let serialPort = ORSSerialPort(path:"/dev/cu.KeySerial1")

详情: Objective-C工厂方法

Details: The Objective-C factory method

+ (ORSSerialPort *)serialPortWithPath:(NSString *)devicePath;

映射到Swift为

init!(path devicePath: String!) -> ORSSerialPort

这在与Objective-C API进行交互(感谢 Nate Cook !):


为了一致性和简单性,Objective-方法映射
作为方便初始化在Swift。这个映射允许它们与
一起使用,具有与初始化器相同的简洁,清晰的语法。

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.

这意味着工厂方法映射到与
Objective-C init方法

That means that the factory method is mapped to the same Swift method as the Objective-C init method

- (id)initWithPath:(NSString *)devicePath;

两者都将从Swift调用

Both would be called from Swift as

let serialPort = ORSSerialPort(path:"/dev/cu.KeySerial1")

,结果是调用 init 方法。因此,不能从Swift调用
factory 方法。

and it turns out that this calls the init method. As a consequence, the factory method cannot be called from Swift.

这篇关于使用Objective-C工厂方法在Swift中创建对象会产生编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆