gpt4 book ai didi

swift - 将泛型添加到递归枚举时: compiler can not infer type

转载 作者:行者123 更新时间:2023-11-30 13:38:48 25 4
gpt4 key购买 nike

根据 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))

最佳答案

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

extension Int: Summable, Multipliable {}

关于swift - 将泛型添加到递归枚举时: compiler can not infer type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com