Dynamic 是否可以使用动态运算符创建动态算术表达式?

Dynamic 是否可以使用动态运算符创建动态算术表达式?,dynamic,swift,operators,Dynamic,Swift,Operators,我想用一个动态运算符创建一个动态算术表达式 我对斯威夫特很陌生,下面的内容完全是假的,但我想的是: 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 )

我想用一个动态运算符创建一个动态算术表达式

我对斯威夫特很陌生,下面的内容完全是假的,但我想的是:

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

不知何故(不定义操作函数/方法)也可能出现类似的情况吗?

最接近的情况是使用运算符的自定义字符,然后使用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();
协议算法{
func+(a:Self,b:Self)->Self
func-(a:Self,b:Self)->Self
func*(a:Self,b:Self)->Self
}
扩展名Int:算术{}
扩展双精度:算术{}
扩展浮点:算术{}
类表达式{
设1:T
设2:T
let算术运算符:字符
init(a操作数a:T,b操作数b:T,o算术运算符:字符){
操作数1=操作数A
操作数2=操作数B
self.arithmeticOperator=算术运算符
}
func calculate()->T{
开关算术运算符{
格“+”:
返回操作数1+2
案例“*”:
返回操作数1*2
案例“-”:
返回操作数1-操作数2
违约:
归零
}
}
}
var expr=expr(a:2,b:5,o:“+”;
expr.calculate();

接受类型为
(Double,Double)->Double的lambda
。然后稍后调用它,例如,
算术运算符(操作数A、操作数B)
。有关此技术的简要概述,请参阅。然后这个函数可以在别处定义,并用作Expr(2,5,Operators.MUL)@user2864740我明白你的意思了,是的。也许我真的应该走这条路。我实际上是在试图避免创建函数(不确定确切原因;可能是懒散:),但我可以试一试。谢谢。看起来已经很整洁了。不过,在本例中,我不完全确定协议
算术
中方法的用法。你介意详细介绍一下吗?