Enum comparison

Overview:

  • I have 2 enums Shape and Vehicle as mentioned below

Question:

  1. How can I determine the boolean value if a certain instance of Vehicle is a car?
  2. I have implemented a function called isCar, just wondering if there is a better way to get the boolean value?
  3. Let me know if making it Equatable or any other way helps?

Note: Based on my requirement it needs to be a Bool because the function accepts only accepts a Bool

enum Shape {
    case circle
    case square
    case triangle
}

enum Vehicle {
    case car(Shape)
    case truck
    
    var isCar: Bool {
        if case .car = self {
            return true
        } else {
            return false
        }
    }
}

let v1 : Vehicle = .car(.circle)

let b1: Bool = v1.isCar //true

Currently what you do (or a very similar code with a switch instead of if) is the best way.

(Equatable could help if you cheat (e.g.: let isCar = vehicle != truck), but that's not good in general case (just consider you add another "case lorry" one day) so I won't bother.)

2 Likes

i almost never store Bools, if you need to encode that information, why not just pass around the original Vehicle instance?

let vehicleKind:Vehicle = v1 

if case .car(_) = vehicleKind 
{
}
else 
{
}
1 Like

Thanks a lot @tera and @taylorswift

@taylorswift the reason I needed bool is because I was using it in SwiftUI in a function func disabled(_ disabled: Bool) -> some View