How to use a switch case with type checkin

I'm trying to test swift enums by extending the ArithmeticExpression from the example with variables but can't get it to work. Any help appreciated:

enum ArithmeticExpression: CustomStringConvertible {
    case number(Int)
    case variable(Character)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)

    func eval() -> ArithmeticExpression {
        switch self {
        case .number(let n):
            return self
        case .variable(let c):
            return self
        case .addition(.number, .number):      // HERE I want to access the numbers as e1 and e2
            return ArithmeticExpression.number(e1 + e2)    // Won't work because e1 and e2 are not defined
        case let .multiplication(e1, e2):          // SAME HERE
            return ArithmeticExpression.number(e1 * e2)
        }
    }
}

You are close, you just have to repeat the 'inner bindings' in the case, see what you did for the basic number(let n) case and substitute in like so:

case .addition(.number(let e1), .number(let e2)):

You can also write this as case let .addition(.number(e1), .number(e2)): if you want to avoid writing let for each variable individually.

1 Like

I've been trying various combinations of as, in, where for 30 minutes and couldn't quite get it right. This makes sense and looks really clean, thanks a lot!

Terms of Service

Privacy Policy

Cookie Policy