我想用动态算子创建一个动态算术表达式。
我对迅捷很新,以下是完全虚假的,但我想的是:
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
类似的东西是否可行,不知何故(没有定义操作函数/方法)?
答案 0 :(得分:2)
最接近的是,我可以使用自定义字符作为运算符,然后使用switch case来计算表达式,
protocol Arithmetic{
func + (a: Self, b: Self) -> Self
func - (a:Self, b: Self ) -> Self
func * (a:Self, b: Self ) -> Self
}
extension Int: Arithmetic {}
extension Double: Arithmetic {}
extension Float: Arithmetic {}
class Expr<T:Arithmetic>{
let operand1: T
let operand2: T
let arithmeticOperator: Character
init( a operandA:T, b operandB:T, o arithmeticOperator:Character) {
operand1 = operandA
operand2 = operandB
self.arithmeticOperator = arithmeticOperator
}
func calculate() -> T? {
switch arithmeticOperator{
case "+":
return operand1 + operand2
case "*":
return operand1 * operand2
case "-":
return operand1 - operand2
default:
return nil
}
}
}
var expr = Expr( a: 2, b: 5, o: "+" );
expr.calculate();