0
從遞歸枚舉下的Swift手冊中的示例中,我嘗試向枚舉中添加泛型類型,並且編譯器無法推斷出我傳遞的類型到評估功能。我能做些什麼來改變代碼來編譯?這是編譯器的錯誤還是限制?在遞歸枚舉中添加泛型時:編譯器無法推斷類型
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))