swiftenumsswitch-statementassociated-value

Swift Switch case on enum with Classes


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?


Solution

  • 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.