gpt4 book ai didi

ios - Swift - 为 NSExpression 创建自定义函数

转载 作者:行者123 更新时间:2023-11-28 14:26:59 27 4
gpt4 key购买 nike

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

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

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

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

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.

非常感谢

最佳答案

你需要使用@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

关于ios - Swift - 为 NSExpression 创建自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51488221/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com