IOS/Objective-C/Swift/Speech: Specify Locale when declaring SFSpeech Recognizer variable

#1
I am trying to translate some Swift which I am just learning to Objective-C for a Speech project.
Swift apparently allows you to specify the locale of a speechRecognizer when declaring the variable as follows:
Mã:
private let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))
Is it possible to do this in Objective-C? Right now I have declared a variable in the interface:
Mã:
SFSpeechRecognizer *speechRecognizer;
And then set the locale later:
Mã:
speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
Ideally, I'd like to do it at the outset in the declaration ibut I am fuzzy on the difference between what Swift and Objective-C are really doing.
Thanks for any suggestions or insights.
 

Admin

Administrator
Thành viên BQT
#2
Think of the Swift call being structured in this order:
Mã:
// 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)
Then comparing the Swift code to Objective-C:
Mã:
// 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"]];
You can re-write the objective-c call to look like this if your prefer to make it into a single line:
Mã:
SFSpeechRecognizer *speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
There is nothing wrong with either approach, it is just that Swift can infer the variable type, so there is no need to create an empty variable before the speech recognizer is initiated. Objective-C can NOT infer variable type, so the command may have been split up just to make the line a bit shorter.
 
Top