简体   繁体   中英

Conversion to swift from objective-c

I'm currently trying to convert the objective-c code to swift of the sample app provided by openEars. However there is this one line of code :

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

How is this written in swift?

It was defined like this in the framework:

+ (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;

However I did try something like this:

OEPocketsphinxController(TRUE, error: nil)

The compiler error was:

Swift Compiler Error Expected declaration

The Swift code you've called would look like this in Objective-C:

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

Sort of...

You're trying to call a constructor which does not exist. Instead, we must go through the sharedInstance :

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

sharedInstance() is a class method of the OEPocketsphinxController class which returns an instance of the OEPocketsphinxController .

setActive(:error:) is an instance method of the OEPocketsphinxController class and must be called on an instance of this class.

So, we want to use sharedInstance() to get an instance on which to call the setActive(:error:) method on.

The following two pieces of code are exactly equivalent:

Swift:

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

Objective-C:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM