Search code examples
swiftxcodeswitch-statementassociated-value

Unwrapping associated value for all cases in switch


I have an enum similar to this, where all cases contain the same associated value content:

enum RowType {
    case single(_ content: [Any])
    case double(_ content: [Any])
    case triple(_ content: [Any])
    ...
}

I know I could just use a struct with a rowType and a content attribute, but let's please not discuss this, but rather have a look at the following: When I want to switch all the cases, I could of course do this:

switch row {
case .single(let content):
    // do anything
    break
case .double(let content):
    // ...
...
}

or even:

switch row {
case .single(let content), .double(let content), ...:
    // do the same thing for all cases
    break
}

Now my enum contains a few more cases and is likely to grow further while under development, so it's inconvenient for me to list all cases in the same case statement just to unwrap the content argument.

So I got curious and wondered: Can I somehow "wildcard" the enum case itself and still unwrap the content field? Like a default case with associated value...

I was hoping to be able to do something like ...

switch row {
case _(let content):
    // do something
    break
}

... or maybe accessing the associated value in the default case.

I did a bit of research but couldn't find an answer, so I'm excited for your thoughts.


Solution

  • Try this in Playground.

    enum RowType {
    case single(_ content: [Any])
    case double(_ content: [Any])
    case triple(_ content: [Any])
    case noVal
    
    var associatedValue: Any? {
        get {
            let mirror = Mirror(reflecting: self)
            if let associated = mirror.children.first {
                return  associated.value
            }
            print("WARNING: Enum option of \(self) does not have an associated value")
            return  nil
        }
      }
    }
    
    let row : RowType = .double([1,2,3])
    let rowNoVal : RowType = .noVal
    row.associatedValue
    rowNoVal.associatedValue