Adopting Equatable Protocol for Enum with nested Enum values

混江龙づ霸主 提交于 2020-01-04 05:36:12

问题


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?


回答1:


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



回答2:


Your Vehicle is not really a valid enum - it certainly does not have any enumeration values. Car and Bike are simply type declarations, and Vehicle is a scope for them. That's why

let value = Vehicle.Car.BMW(2500) 

works - but value's type is not a Vehicle it's a Vehicle.Car.




回答3:


the trouble is, that

let a = Vehicle.Car.BMW(100)

is NOT constant of type Vehicle, but Vehicle.Car ... etc. How would you like to create a variable or constant of Vehicle from your example?

Take in account, that enum Vehicle has NO case at all ...



来源:https://stackoverflow.com/questions/35505655/adopting-equatable-protocol-for-enum-with-nested-enum-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!