Swift Numbers Name Text to Int

2019-03-02 06:02发布

问题:

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".

回答1:

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