As Price Ringo suggests, a recursive enum is definitely the right tool here. I would build it along these lines:
enum Operator {
case Add
case Subtract
}
enum Expression {
indirect case Operation(Operator, Expression, Expression)
case Value(Int)
}
let expression = Expression.Operation(.Add,
.Value(5),
.Operation(.Subtract,
.Value(1),
.Operation(.Add, .Value(34), .Value(1))))
If you wanted to, you could do it Price's way with functions, and that's probably pretty clever, but I suspect would actually be more of a headache to parse. But if you wanted to, it'd look like this:
enum Expression {
indirect case Operation((Int, Int) -> Int, Expression, Expression)
case Value(Int)
}
let expression = Expression.Operation(+,
.Value(5),
.Operation(-,
.Value(1),
.Operation(+, .Value(34), .Value(1))))
Alternately, you could create an Operator type rather than passing in functions. That's how I'd probably recommend going unless you really want to be able tow