2014-09-27 138 views
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 

将事情是可能的,以某种方式(不定义操作功能/方法,那是)?

+0

接受类型的拉姆达'(双人间,双人间) - >双'。然后稍后调用它,例如'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

+0

@ user2864740我明白你的意思了,是的。也许我应该走这条路。我实际上是在试图避免创建函数(不确定为什么;可能是懒惰:)),但我可以给这个镜头。 – Codifier 2014-09-27 00:43:14

回答

2

最接近的,我可以说是使用自定义字符为运营商提供,然后使用开关情况来计算表达式,

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(); 
+0

谢谢。这看起来很整齐。尽管如此,我并不完全确定协议“算术”中方法的用法。你介意扩展吗? – Codifier 2014-09-27 01:48:11