【问题标题】:How to catch exception when use NSExpression (swift 3)使用 NSExpression (swift 3) 时如何捕获异常
【发布时间】:2017-04-15 03:09:04
【问题描述】:
    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)))”时,这是一个错误,我不知道如何捕获异常。谢谢!

【问题讨论】:

  • 您的问题是不平衡的括号“5 * (1+4)”会起作用。我投票关闭它作为一个错字
  • ex: var colculation = "5*(1+4)" funccalculatorFromString 将返回结果 25 ,如果输入等于 "5*(1+4)))",如何捕获异常。
  • 注意不需要尝试

标签: exception swift3 try-catch nsexpression


【解决方案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))")
}

【讨论】:

  • 您描述的模式是用于“错误处理”。 OP 试图解决的问题是“异常处理”,根据 Using Swift with Cocoa and Objective-C 一书,目前无法在纯 Swift 中完成。处理这个问题的唯一方法是使用 Objective-C。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2021-08-22
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
相关资源
最近更新 更多