Swift 枚举:表达式模式匹配问题



我一直在尝试将自定义关联值与枚举中的字符串混合使用,但无法做到这一点。当我尝试在枚举上应用开关大小写时,出现此错误:类型"水果"的表达式模式无法匹配类型"水果"的值

是因为字符串是值类型,因此 Swift 能够比较它们,但不能比较作为引用类型的 Fruit 的自定义类对象吗?

class Fruit{
let name: String?
let energyKcl: Double?
let costPerKg: Double?
init(name:String, energyKcl: Double, costPerKg: Double) {
self.name = name
self.energyKcl = energyKcl
self.costPerKg = costPerKg
}
}
enum Calorie {
case fruit(Fruit)
case chocolate (String)
case dairy(String)
case Nuts(String)
}

let banana = Fruit.init(name: "Banana", energyKcl: 100, costPerKg: 10)
func prepareBreakfast(calories: Calorie){
switch calories {
case .chocolate("Dark"):
print("Dark")
case .chocolate("White"):
print("White")
case .fruit(banana): //Error: Expression pattern of type 'Fruit' cannot match values of type 'Fruit'
print("banana")
default:
print ("Not available")
}
}
prepareBreakfast(calories: .fruit(banana))

不,问题是没有平等协议,自定义类是无法比较的

extension Fruit: Equatable {
static func == (lhs: Fruit, rhs: Fruit) -> Bool {
return lhs.name == rhs.name
&& lhs.energyKcl == rhs.energyKcl
&& lhs.costPerKg == rhs.costPerKg
}
}

模式匹配在内部使用Equatable,因此您应该更改Fruit类:

extension Fruit: Equatable {
static func == (lhs: Fruit, rhs: Fruit) -> Bool {
return lhs.name == rhs.name // or every field if you want
}
}

如果要使用该引用,只需将==func 更改为在两个引用相等时返回 true,但我认为这不是一个好主意:

static func == (lhs: Fruit, rhs: Fruit) -> Bool {
return lhs === rhs
}

在你的代码中,

替换prepareBreakfast(calories:)方法中的以下行,

case .fruit(banana):

case .fruit(let banana):

你很好去。我认为您的代码没有任何其他问题。它在我的最后工作得很好。

最新更新