Advertisement
Guest User

Untitled

a guest
Jul 16th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.12 KB | None | 0 0
  1. // 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 ?
  2.  
  3. recognitionRequest?.shouldReportPartialResults = true
  4.         recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest!, resultHandler: { (result, error) in
  5.             var isFinal = false
  6.             if result != nil {
  7.                 guard let stringResult = result?.bestTranscription.formattedString else {
  8.                     return
  9.                 }
  10.                 self.inputLabel.text = stringResult
  11.                 isFinal = (result?.isFinal)!
  12.                 if isFinal == true {
  13.                     print(stringResult)
  14.                     self.calculate(string: stringResult)
  15.                 }
  16.             }
  17.  
  18.  
  19. /////////////
  20.  
  21. // 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?
  22.  
  23.  
  24. private func calculate(string: String) {
  25.         if string.contains("×") || string.contains("+") || string.contains("-") {
  26.             let stringToCalculate = string.replacingOccurrences(of: "×", with: "*")
  27.             guard let finalScore = NSExpression(format: stringToCalculate).expressionValue(with: nil, context: nil) else { return }
  28.             outputLabel.text = String(describing: finalScore)
  29.         } else {
  30.             outputLabel.text = "Are you sure it's mathematical evaluation ?"
  31.         }
  32.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement