0
    import UIKit


func calculatorFromString(colculation:String)->Double{
    let mathExpression = try NSExpression(format: colculation)
    let mathValue = mathExpression.expressionValue(with: nil, context: nil) as? Double
        return mathValue!
}

calculatorFromString(colculation: "5*(1+4)")

when I set colculation equal "5*(1+4)))", this is a error and I dont know how to catch exception. Thank you!

Wind
  • 11
  • 3
  • Your problem is the unbalanced parentheses "5 * (1+4)" would work. I am voting to close it as a typo – Leo Dabus Apr 15 '17 at 03:20
  • ex: var colculation = "5*(1+4)" func calculatorFromString will return a result 25 , if input equal "5*(1+4)))", how to catch exception. – Wind Apr 15 '17 at 03:22
  • Note that try it is not needed – Leo Dabus Apr 15 '17 at 03:42
  • Possible duplicate of [Catching NSException in Swift](https://stackoverflow.com/questions/32758811/catching-nsexception-in-swift) – Can Jan 18 '18 at 20:26

1 Answers1

-1

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

pseudo Code

do {
    try expression
    statements
} catch pattern 1 {
    statements
} catch pattern 2 where condition {
    statements
}

hope it's help you

do{

try(calculatorFromString(colculation: "5*(1+4)"))

}catch {
calculatorFromString(colculation: "\(5 * (1 + 4))")
}
kishu mewara
  • 2,434
  • 11
  • 27
  • The pattern you are describing is for "error handling". The problem OP is trying to solve is "exception handling", which cannot be done in pure Swift at this point per the _Using Swift with Cocoa and Objective-C_ book. The only way to handle this is to use Objective-C. – oriyentel Aug 04 '17 at 15:09