gpt4 book ai didi

swift - 我可以强制 NSExpression 和 expressionValue 以某种方式假设 Doubles 而不是 Ints 吗?

转载 作者:搜寻专家 更新时间:2023-10-31 22:18:48 25 4
gpt4 key购买 nike

我正在尝试对字符串进行数学运算。

当我用 NSExpression 把一个字符串变成一个数学问题,然后用 expressionValue 得到结果时,Swift 假设我想要一个整数。考虑这两个 Playground 示例:

let currentCalculation = "10 / 6"
let currentExpression = NSExpression(format: currentCalculation)
print(currentExpression) // 10 / 6
if let result = currentExpression.expressionValue(with: nil, context: nil) as? Double {
print(result) // 1
}

let anotherCalculation = "10.0 / 6.0"
let anotherExpression = NSExpression(format: anotherCalculation)
print(anotherExpression) // 10 / 6
if let result = anotherExpression.expressionValue(with: nil, context: nil) as? Double {
print(result) // 1.666666667
}

我应该怎么做才能始终获得 Double 作为结果?我不想提前解析字符串。

非常有趣的是,第二个示例将“anotherExpression”转换为 Integers,但结果仍返回 Double。

最佳答案

您最好使用第 3 方表达式解析器/求值器,例如DDMathParser .NSExpression 非常有限,没有强制 float 的选项积分评价。

如果你想(或不得不)坚持NSExpression:这是一个(递归)替换所有常量的可能解决方案表达式中的值按其浮点值:

extension NSExpression {

func toFloatingPoint() -> NSExpression {
switch expressionType {
case .constantValue:
if let value = constantValue as? NSNumber {
return NSExpression(forConstantValue: NSNumber(value: value.doubleValue))
}
case .function:
let newArgs = arguments.map { $0.map { $0.toFloatingPoint() } }
return NSExpression(forFunction: operand, selectorName: function, arguments: newArgs)
case .conditional:
return NSExpression(forConditional: predicate, trueExpression: self.true.toFloatingPoint(), falseExpression: self.false.toFloatingPoint())
case .unionSet:
return NSExpression(forUnionSet: left.toFloatingPoint(), with: right.toFloatingPoint())
case .intersectSet:
return NSExpression(forIntersectSet: left.toFloatingPoint(), with: right.toFloatingPoint())
case .minusSet:
return NSExpression(forMinusSet: left.toFloatingPoint(), with: right.toFloatingPoint())
case .subquery:
if let subQuery = collection as? NSExpression {
return NSExpression(forSubquery: subQuery.toFloatingPoint(), usingIteratorVariable: variable, predicate: predicate)
}
case .aggregate:
if let subExpressions = collection as? [NSExpression] {
return NSExpression(forAggregate: subExpressions.map { $0.toFloatingPoint() })
}
case .anyKey:
fatalError("anyKey not yet implemented")
case .block:
fatalError("block not yet implemented")
case .evaluatedObject, .variable, .keyPath:
break // Nothing to do here
}
return self
}
}

例子:

let expression = NSExpression(format: "10/6+3/4")
if let result = expression.toFloatingPoint().expressionValue(with: nil, context: nil) as? Double {
print("result:", result) // 2.41666666666667
}

这适用于使用算术运算符和函数的“简单”表达式以及一些“高级”表达式类型(并集、交集...)。如有必要,可以添加剩余的转化。

关于swift - 我可以强制 NSExpression 和 expressionValue 以某种方式假设 Doubles 而不是 Ints 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46550658/

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