我正在尝试将一些我刚刚学习的 Swift 翻译成 Objective-C 用于语音项目。
Swift 显然允许您在声明变量时指定 speechRecognition r 的区域设置,如下所示:
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 真正在做什么之间的区别很模糊。
感谢您的任何建议或见解。
考虑按以下顺序构建的 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 无法推断变量类型,因此命令可能被拆分只是为了让行更短一点。