vendredi 8 janvier 2016

enum pattern matching in Swift

I just started learn Swift and trying to understand pattern matching.

I found the next example:

private enum Entities{
  case Operand(Double)
  case UnaryOperation(Double -> Double)
  case BinaryOperation((Double, Double) -> Double)
}

and later I use pattern matching to figure out the type of Entity

func evaluate(entity: Entities) -> Double? {
    switch entity{
    case .Operand(let operand):
        return operand;

    case .UnaryOperation(let operation):
        return operation(prevExtractedOperand1);

    case .BynaryOperation(let operation):
        return operation(prevExtractedOperand1, prevExtractedOperand2);
    }
}

Syntax of getting associated value seems little bit weird, but it works fine.

After that I found, that it is possible to use pattern matching in if statement, so I tried to do the same with if

if case entity = .Operand(let operand){
    return operand
}

but compiler throws error Expected ',' separator, which, I suspect, has nothing common with real reason of the error.

Could you pls help me to understand, what is wrong with my attempt to use pattern matching in if statement?

Aucun commentaire:

Enregistrer un commentaire