Swift Switch case on enum with Classes

2k Views Asked by At

This is the first time I use this kind of enums, enum with associated value type, I need to make a switch statement depending on the object's type, I cannot managed to do it, this is the enum:

enum TypeEnum {
    case foo(FooClass)
    case doo(DooClass)
    case roo(RooClass)
}

My object has a variable of type TypeEnum, now I need to check which kind of object is in the enum:

if let anObject = object as? TypeEnum {

  switch anObject {
  case .foo(???):
     return true
    ...
    default:
      return false
    }

 }

I have no idea what to put instead of ???. Xcode tells me to put something, but I just want to switch on .foo.

Any ideas?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use let to capture the associated values for that:

switch anObject {
case .foo(let fooObj):
    ...
}

or nothing at all if you just don't care about them:

switch anObject {
case .foo:
    ...
}

Please be sure to check the Swift Programming Language book for further details.

0
On

You could use the underscore to indicate that you aren't interested in the associated type:

case .foo(_):
...