Swift Numbers Name Text to Int

走远了吗. 提交于 2019-12-02 11:47:35

问题


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


来源:https://stackoverflow.com/questions/46856297/swift-numbers-name-text-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!