0
我想用动态运算符创建动态算术表达式。是否可以使用动态运算符创建动态算术表达式?
我很新的快捷,下面是完整的假,但我在想沿着线的东西:
类似class Expr {
var operandA:Double = 0;
var operandB:Double = 0;
var arithmeticOperator:operator = +; // total bogus
init(a operandA:Double, b operandB:Double, o arithmeticOperator:operator) {
self.operandA = operandA;
self.operandB = operandB;
self.arithmeticOperator = arithmeticOperator;
}
func calculate() -> Double {
return self.operandA self.arithmeticOperator self.operandB; // evaluate the expression, somehow
}
}
var expr = Expr(a: 2, b: 5, o: *);
expr.calculate(); // 10
将事情是可能的,以某种方式(不定义操作功能/方法,那是)?
接受类型的拉姆达'(双人间,双人间) - >双'。然后稍后调用它,例如'arithmeticOperator(operandA,operandB)'。有关此技术的简要概述,请参见[Swift语言中的函数式编程](https://medium.com/swift-programming/2-functional-swift-c98be9533183)。然后这个函数可以在其他地方定义,并用作'Expr(2,5,Operators.MUL)'。 – user2864740 2014-09-27 00:28:45
@ user2864740我明白你的意思了,是的。也许我应该走这条路。我实际上是在试图避免创建函数(不确定为什么;可能是懒惰:)),但我可以给这个镜头。 – Codifier 2014-09-27 00:43:14