2

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?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
user2434385
  • 281
  • 1
  • 3
  • 16
  • is there something else being returned besides true and false? If the answer is no then I would use `isKind(of:)` or `isMember(of:)` as for your class right now, you need to fill in .foo with the instance of class you want to use, which is not what you probably want – Knight0fDragon Jul 05 '17 at 13:39
  • 3
    [Swift Language Guide: Enumerations](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-ID145) Please read the the *Associated Values* section. – vadian Jul 05 '17 at 13:54

2 Answers2

5

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.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
0

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

case .foo(_):
...
Abizern
  • 146,289
  • 39
  • 203
  • 257