1

I have this

enum MyEnum {
  case one
  case two
}

and this

var array:[MyEnum] = [.one]

and later

func add(_ case:MyEnum) {
  if array.contains(case) { return }
  array.append(case)
}

So far so good.

Then I have added a third option to the enum

enum MyEnum {
  case one
  case two
  case three(user:User)
}

then the line

if array.contains(case) { return }

is giving this error

Referencing instance method 'contains' on 'Sequence' requires that 'MyEnum' conform to 'Equatable'

I guess that the problem is this

  1. contains can easily see if .one is equal to .two or not, so it can check if these elements are on array.
  2. contains cannot easily see if .three(user:"bob") is the same as .three(user:"carl"), right?

I don't care which user is, I just want to compare if array has an entry three or not.

If the array is [.two, .one, .three(user:"bob)] and I try to append .three("user:"carl") I want the line if array.contains(.three("user:"carl"))to return true.

How do I do that?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Ronnie
  • 332
  • 2
  • 11
  • 2
    Is `User` equatable? If it is, just conform `MyEnum` to `Equatable` and you are done. – Sweeper Jan 22 '21 at 10:33
  • BRILLIANT. I hate when Xcode does not say the real reason behind the issues. Thanks. Please make this an answer. – Ronnie Jan 22 '21 at 10:36
  • @Sweeper Indeed, but I would have created maybe a `isOfSameType(_:)` instead on `MyEnum`, since it's supposed to return true even if the User is different. It depends if later the user needs a more "usual equatable". – Larme Jan 22 '21 at 10:38
  • @Larme - can you explain that with code? Sorry, I am new to this equatable thing. – Ronnie Jan 22 '21 at 10:41
  • @Larme's comment made me realise that I misread the question. See the second dupe for how to compare enums without considering their associated values, and use that to conform to `Equatable`. – Sweeper Jan 22 '21 at 10:43
  • 1
    https://pastebin.com/QwjGTanZ – Larme Jan 22 '21 at 10:46

0 Answers0