代码之家  ›  专栏  ›  技术社区  ›  user6631314

IOS/Objective-C/Swift/Speech:声明SFSpeech Recognizer变量时指定区域设置

  •  0
  • user6631314  · 技术社区  · 6 年前

    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到底在做什么。

    谢谢你的建议和见解。

    1 回复  |  直到 6 年前
        1
  •  1
  •   CodeBender    6 年前

    想象一下,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 推断变量类型,因此命令可能被拆分,只是为了使行稍微短一点。

    推荐文章