【发布时间】:2014-11-10 14:46:39
【问题描述】:
周末我开始玩 Swift。我正在尝试构建一个类似应用程序的计算器。因此,我想建模一棵表达式树。
整个 swift 编译器套件/xcode 似乎仍然非常不稳定。我每隔几分钟就会崩溃一次。 这就是为什么我想知道我的代码是错误的还是只是编译器有问题。
这两个协议编译正常
protocol BinaryOperator {
typealias LeftType
typealias RightType
typealias ResultType
func apply(left: LeftType, right: RightType) -> ResultType
}
protocol UnaryOperator {
typealias SourceType
typealias ResultType
func apply(SourceType) -> ResultType
}
但是添加以下类,编译器会在类的第一行出现分段错误而崩溃。我怀疑它是由 where 子句引起的,因为如果我删除它,编译器不会再崩溃,但由于类型不匹配,它仍然无法编译。
class BinaryExpression<O:BinaryOperator, L:Expression, R:Expression
where L.ResultType==O.LeftType, R.ResultType==O.RightType> : Expression {
typealias ResultType = O.ResultType
let op : O
let lhs : L
let rhs : R
init(op o : O, left : L, right: R) {
op = o
lhs = left
rhs = right
}
func eval() -> ResultType {
let left : O.LeftType = lhs.eval()
let right : O.RightType = rhs.eval()
return op.apply(left, right: right)
}
}
【问题讨论】: