将泛型添加到递归枚举时:编译器无法推断类型

时间:2016-03-05 09:14:16

标签: swift

从递归枚举下的Swift手册中的示例,我试图将一个泛型类型添加到枚举中,并且编译器无法推断我传递给evaluate函数的类型。如何更改要编译的代码?这是编译器的错误还是限制?

protocol Summable {
    func +(lhs: Self, rhs: Self) -> Self
}

protocol Multipliable {
    func *(lhs: Self, rhs: Self) -> Self
}

indirect enum ArithmeticExpression<T: protocol<Summable, Multipliable>> {
    case Number(T)
    case Addition(ArithmeticExpression, ArithmeticExpression)
    case Multiplication(ArithmeticExpression, ArithmeticExpression)
}

func evaluate<T>(expression: ArithmeticExpression<T>) -> T {
    switch expression {
    case .Number(let value):
        return value
    case .Addition(let left, let right):
        return evaluate(left) + evaluate(right)
    case .Multiplication(let left, let right):
        return evaluate(left) * evaluate(right)
    }
}


let five = ArithmeticExpression.Number(5)
let four = ArithmeticExpression.Number(4)
let sum = ArithmeticExpression.Addition(five, four)
let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2))
print(evaluate(product))

1 个答案:

答案 0 :(得分:0)

我刚刚找到了答案,实际上非常简单:

extension Int: Summable, Multipliable {}