1

Currently, we have the following enum.

enum Animal : Equatable {
    case dog(String)
    case cat(Int)
}

If we want to compare enum type and its associate value, we can simply do this.

let dog0 = Animal.dog("mimi")
let dog1 = Animal.dog("hihi")

if (dog0 == dog1) {
    print("same dog type and same name")
} else {
    print("not same dog")
}

not same dog will be printed.

What if, we also want to have the ability, to compare enum type only and ignore its associated value?

if (???) {
    print("same dog type (might be different name)")
} else {
    print("not same dog")
}

May I know, what kind of technique we can use?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • You could add a computed variable called `typeID` which returns an `Int`. This computed variable could return the same number for the same type ignoring the associated value. Then you could simply check `dog0.typeID == dog1.typeID` – user1046037 Sep 03 '20 at 06:01

0 Answers0