想象一下,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代码与目标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可以推断变量类型,所以在启动语音识别器之前不需要创建空变量。目标C can
推断变量类型,因此命令可能被拆分,只是为了使行稍微短一点。