gpt4 book ai didi

swift - Swift 中的枚举模式匹配

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:02 25 4
gpt4 key购买 nike

我刚开始学习 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
}

但是编译器抛出错误 Expected ',' separator,我怀疑这与错误的真正原因没有任何共同之处。

你能帮我理解吗,我尝试在 if 语句中使用模式匹配有什么问题?

最佳答案

我想你想要的语法是这样的:

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

或者这个:

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

要绑定(bind)的变量需要在 let= 符号的左侧。

关于swift - Swift 中的枚举模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34684084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com