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

当我将 colculation 设置为“5*(1+4)))”时,这是一个错误,我不知道如何捕获异常。谢谢!

4

1 回答 1

-1

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

伪代码

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

希望对你有帮助

do{

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

}catch {
calculatorFromString(colculation: "\(5 * (1 + 4))")
}
于 2017-04-15T06:39:42.083 回答