Swift-为NSExpression创建自定义函数

时间:2018-07-23 22:55:45

标签: ios swift function

我正在使用NSexpression评估字符串形式的数学方程式,对于我作为一个初学者正在从事的项目,示例字符串为:

"12 + 3 - sqrt(4) * 9"

这似乎对基本的数学运算非常有效,但不适用于我需要的更高级的东西,例如立方根和阶乘。

我尝试创建自定义函数作为NSnumber的扩展,但是我一直空白。关于如何解决这个问题的任何建议,或者一种完全不同的方法来评估字符串形式的方程式?这是我在操场上尝试过的:

import UIKit

public extension NSNumber {

    func factorial() -> NSNumber {
        var xDouble = self as! Double
        var index = xDouble - 1
        while index > 1 {
            xDouble = xDouble * index
            index = index - 1
        }
        return xDouble as NSNumber
    }
}

let equation = "function(3, 'factorial')"
let expression = NSExpression(format: equation)
let result = expression.expressionValue(with: nil, context: nil) as! Double

但是,这将返回以下错误:

error: Execution was interrupted, reason: signal SIGABRT.
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

非常感谢

1 个答案:

答案 0 :(得分:1)

您需要使用@objc

import UIKit

@objc
public extension NSNumber {

    func factorial() -> NSNumber {
        var xDouble = self as! Double
        var index = xDouble - 1
        while index > 1 {
            xDouble = xDouble * index
            index = index - 1
        }
        return xDouble as NSNumber
    }
}

let equation = "function(3, 'factorial')"
let expression = NSExpression(format: equation)
let result = expression.expressionValue(with: nil, context: nil) as! Double

https://qiita.com/on0z/items/ac7074b52bfc049dfbe3