Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
How to declare an `enum` of `enum` that allows for "flattened" `switch` statement?

Optional in Swift allows for magic where switch-ing over an optional enum flattens the cases into a single switch statement.

Given:

enum Foo {
    case bar, baz
}

You can:

let foo: Foo? = .bar
switch foo {
case .bar:
    break
case .baz:
    break
case nil:
    break

Here, Optional is an enum and Foo is an enum, but just one single statement is enough to cover all cases of both.

Question: can I declare my own enum inside another enum so that the cases can be handled in a flat way too?

So that I could:

enum Foo<Bar> {
    case nope
    case dope(Bar)
}

enum Baz {
    case yep
}

let b: Foo<Baz> = .dope(.yep)

switch b {
case .nope:
    break
case .yep:
    break
}

Maybe if I call the case Foo.dope as Foo.some? Maybe there is an annotation that I can use?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You could do this with …

switch b {
case .nope: // stuff
case .dope(.yep): // other stuff
case .dope(.someOtherCase): // more stuff
}

Responding to your comment…

Imagine you could flatten it like you said. How would you deal with…

enum Foo {
    case a
    case b(Bar)
    case c(Bar)
}

If you are allowed to exclude the .b from the switch then there is no way to differentiate between .b and .c.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!