Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // So this is the piece of the function that makes magic. I mean speech - to - text. We have 'stringResult' variable that //is string that comes with everything what we say. The problem is, when we want a math evaluation app. So for example when //we say "two plus two multiplied by 7" everything works super fine, but when we say for example "Dog" app needs to know //that it is a word . So is it even possible to make it detect that something is math or a word ?
- recognitionRequest?.shouldReportPartialResults = true
- recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest!, resultHandler: { (result, error) in
- var isFinal = false
- if result != nil {
- guard let stringResult = result?.bestTranscription.formattedString else {
- return
- }
- self.inputLabel.text = stringResult
- isFinal = (result?.isFinal)!
- if isFinal == true {
- print(stringResult)
- self.calculate(string: stringResult)
- }
- }
- /////////////
- // This is calculate function, that is using NSExpression. Currently function looks tottaly awful, but somehow can filter //words and math evaluations by searching for x,+,- in strings. The most perfect way to handle this error would making DO - //TRY - CATCH after guard let, so after casting this variable as NSExpression. If casting succeds - print score, if not - //outputLabel.text = "Are you sure it's mathematical evaluation ?" Or maybe there is another way to make calculations from String?
- private func calculate(string: String) {
- if string.contains("×") || string.contains("+") || string.contains("-") {
- let stringToCalculate = string.replacingOccurrences(of: "×", with: "*")
- guard let finalScore = NSExpression(format: stringToCalculate).expressionValue(with: nil, context: nil) else { return }
- outputLabel.text = String(describing: finalScore)
- } else {
- outputLabel.text = "Are you sure it's mathematical evaluation ?"
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement