0

我目前正在尝试将objective-c 代码转换为openEars 提供的示例应用程序的swift。但是有这一行代码:

[[OEPocketsphinxController sharedInstance] setActive:TRUE error:nil];

这是如何用swift写的?

它在框架中是这样定义的:

+ (OEPocketsphinxController *)sharedInstance;
/**This needs to be called with the value TRUE before setting properties of OEPocketsphinxController for the first time in a session, and again before using OEPocketsphinxController in case it has been called with the value FALSE.*/
- (BOOL)setActive:(BOOL)active error:(NSError **)outError;

但是我确实尝试过这样的事情:

OEPocketsphinxController(TRUE, error: nil)

编译器错误是:

Swift 编译器错误预期声明

4

1 回答 1

4

你调用的 Swift 代码在 Objective-C 中看起来像这样:

[[OEPocketsphinxController alloc] initWith:YES error:nil]

有点...

您正在尝试调用不存在的构造函数。相反,我们必须通过sharedInstance

OEPocketsphinxController.sharedInstance().setActive(true, error: nil)

sharedInstance()是类的类方法,OEPocketsphinxController它返回OEPocketsphinxController.

setActive(:error:)OEPocketsphinxController类的实例方法,必须在此类的实例上调用。

因此,我们想使用sharedInstance()来获取一个实例,在该实例上调用该setActive(:error:)方法。

以下两段代码完全等价:

迅速:

OEPocketsphinxController.sharedInstance().setActive(true, error: nil)

目标-C:

[[OEPocketsphinxController sharedInstance] setActive:TRUE error:nil];
于 2015-06-28T14:23:29.830 回答