Swift中的枚举模式匹配

时间:2016-01-08 18:52:52

标签: swift design-patterns enums matching

我刚开始学习Swift并尝试理解模式匹配。

我找到了下一个例子:

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

以后我使用模式匹配来确定实体的类型

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);
    }
}

获取相关值的语法似乎有点奇怪,但它工作正常。

之后我发现,可以在if语句中使用模式匹配,所以我尝试对if进行相同的操作

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

但编译器抛出错误预期','分隔符,我怀疑,这与错误的真正原因没有任何共同之处。

你能不能帮助我理解,我在if声明中尝试使用模式匹配有什么问题?

1 个答案:

答案 0 :(得分:6)

我认为你想要的语法是:

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

或者这个:

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

要绑定的变量需要位于=let符号的左侧。

相关问题