我正在尝试将我正在学习的一些Swift转换为Objective-C的语音项目。
显然,在声明变量时,使用swift可以指定SpeechRecognizer的语言环境,如下所示:
private let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))
在Objective-C中可以这样做吗?现在,我在接口中声明了一个变量:
SFSpeechRecognizer *speechRecognizer;
然后再设置区域设置:
speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
理想情况下,我想一开始就在声明中这样做,但是我对Swift和Objective-C真正在做什么之间的区别感到模糊。
感谢您的任何建议或见解。
答案 0 :(得分:1)
考虑按以下顺序构造Swift调用:
// Create a Locale object for US English
let locale = Locale.init(identifier: "en-US")
// Create a speech recognizer object for US English
let speechRecognizer = SFSpeechRecognizer(locale: locale)
然后将Swift代码与Objective-C进行比较:
// Here you are create an uninitialized variable of type SFSpeechRecognizer
// this will then hold the SFSpeechRecognizer when you initialize it in the next line
SFSpeechRecognizer *speechRecognizer;
// This is accomplishing the same logic as the above Swift call
speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
如果您希望将其写成一行,可以重新编写Objective-C调用,如下所示:
SFSpeechRecognizer *speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
这两种方法都没有错,只是Swift可以推断变量类型,因此在启动语音识别器之前无需创建空变量。 Objective-C可以不推断变量类型,因此该命令可能已被拆分,只是为了使行短一些。