Thanos
Thanos

Reputation: 854

Adopting Equatable Protocol for Enum with nested Enum values

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?

Upvotes: 2

Views: 620

Answers (3)

Rob Napier
Rob Napier

Reputation: 299275

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

Upvotes: 1

user3441734
user3441734

Reputation: 17534

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 ...

Upvotes: 1

Grimxn
Grimxn

Reputation: 22487

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.

Upvotes: 1

Related Questions