I just implemented SFSpeechRecognizer, because I want it to dictate some numbers, but the issue that I'm encountering is that if I say "one" the result.bestTranscription.formattedString is "one", but if I say "ten" the result throws "10", how can I manage to get single digit numbers to be represented by the actual number not the symphonic "one".
Asked
Active
Viewed 799 times
1 Answers
3
You can use NumberFormatter setting numberStyle
to .spellOut
and use its number(from: String)
to convert your string to number. If you need a string from that number just initialise a new string from it. Make sure if you only want to detect English words (not locale sensitive) to set the formatter locale to "en_US_POSIX"
let string = "one"
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en_US_POSIX") // if you dont set locale it will use current locale so it wont detect one if the language it is not english at the devices locale
numberFormatter.numberStyle = .spellOut
numberFormatter.number(from: string) // 1
Testing another language/locale
let string = "um"
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "pt_BR")
numberFormatter.numberStyle = .spellOut
numberFormatter.number(from: string) // 1

Leo Dabus
- 229,809
- 59
- 489
- 571
-
1Thanks for the quick response, it worked beautifully! – cesar martinez Oct 20 '17 at 20:40
-
Fyi, `numberFormatter.number(from: "One")` returns `nil`: [TIO](https://tio.run/##bVBNa8MwDL37V4ickkvLYKfCroXBWAphsFvxYiUVOFKw5ZX@@sxxs8M@bpbeh/VevNKgj8tC0yxB4SiJnVUSNsajQtRAPMITVC1jVVacpg8MRwmTVcWQsdefm7oxvzg7L731mKkv5VGTQ1YaCMMBKuTzW3c@td3ze9UA7PdAA9wkgRPOF@QvNzkpXMl7SBGhTyFkj28oSkFXgUPFXkEYVx@9IHjLY7JjMaAILArIo6d4AauF4fCTeoyb25/z73Ont5JhF2f0vk16r2Nt4H9BPQSZDluHOdka7cGYOY9ac2iW5Qs) – thisIsTheFoxe Apr 28 '21 at 16:21
-
@thisIsTheFoxe funny AFAIR it used to work on earlier versions. Just use `.lowercased()` if needed – Leo Dabus Apr 28 '21 at 17:18