本文介绍了采用嵌套枚举值的枚举的等价协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这个数据结构:

 枚举车辆:Equable {

enum Car {
案例宝马(Int)
案例奥迪(Int)
}

enum自行车{
案例Ducatti(Int)
案例本田(Int )
}

}

表示各种车辆马力作为其相关价值。



我试图符合 Equable 协议,以便能够执行



我正在尝试:

  func ==(a:Vehicle,b:Vehicle) - > Bool {
switch(a,b){
case(let Car.BMW(hp1),let Car.BMW(hp2)):
return hp1 == hp2
default :
return false
}
}

但编译器抱怨关于无效模式



那么我们如何正确地符合包含嵌套枚举和相关值的枚举协议?

解决方案

正如其他人所指出的,你对嵌套枚举的定义不会创建 Vehicle 的案例。他们只是定义了与名字无关的两种类型。你想做的是这样的:

 枚举车辆:Equable {
enum CarType {
case宝马(Int)
案例奥迪(Int)
}

枚举BikeType {
案例Ducatti(Int)
案例本田(Int)
}

case Car(CarType)
case自行车(BikeType)
}

func ==(a:Vehicle,b:车辆) - > Bool {
switch(a,b){
case(.Car(.BMW(let hp1)),.Car(.BMW(let hp2))):
return hp1 == hp2
默认值:
返回false
}
}

let bmw1 = Vehicle.Car(.BMW(1))
let bmw2 = Vehicle.Car(.BMW(1))
let bmw3 = Vehicle.Car(.BMW(2))
bmw1 == bmw2 // true
bmw2 == bmw3 // false


Assuming we have this datastructure:

enum Vehicle: Equatable {

   enum Car {
       case BMW(Int)
       case Audi(Int)
   }

   enum Bike {
       case Ducatti(Int)
       case Honda(Int)
   }

}

that represents various vehicles with their horsepower as their associated value.

I am trying to conform to the Equatable protocol in order to be able to perform Vehicle equivalence with no success.

I am trying with:

func ==(a: Vehicle, b: Vehicle) -> Bool {
    switch(a, b) {
        case(let Car.BMW(hp1), let Car.BMW(hp2)):
           return hp1 == hp2
        default:
           return false
    }
}

but the compiler complains about invalid pattern.

So how can we properly conform to the Equatable protocol for enums that contain nested enums and associated values?

解决方案

As others have noted, your definition of nested enums does not create cases of Vehicle. They just define two types that have nothing to do with each other except their names. What you're trying to do would look like this:

enum Vehicle: Equatable {
    enum CarType {
        case BMW(Int)
        case Audi(Int)
    }

    enum BikeType {
        case Ducatti(Int)
        case Honda(Int)
    }

    case Car(CarType)
    case Bike(BikeType)
}

func ==(a: Vehicle, b: Vehicle) -> Bool {
    switch (a, b) {
    case (.Car(.BMW(let hp1)), .Car(.BMW(let hp2))):
        return hp1 == hp2
    default:
        return false
    }
}

let bmw1 = Vehicle.Car(.BMW(1))
let bmw2 = Vehicle.Car(.BMW(1))
let bmw3 = Vehicle.Car(.BMW(2))
bmw1 == bmw2 // true
bmw2 == bmw3 // false

这篇关于采用嵌套枚举值的枚举的等价协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:01