0

I want to define an enum case which is recursively defined by a particular instance of the same enum

enum Menu {
  case item(String)
  case submenu([.item]) // i want a submenu to be defined by an array of items
}

the submenu case isn't correct:

case submenu([.item])

how can I confine it?

1 Answer 1

3

All cases of an enum are of the same enum type, so you cannot declare an Array that can only hold a specific case of an enum.

However, you can achieve your goals by creating 2 enums instead of one and making the Menu.submenu enum case take the other enum as its associated value.

enum Menu {
    case item(MenuItem)
    case submenu([MenuItem])
}

enum MenuItem {
  case item(String)
}

Then you can use it like

let menu = Menu.item(.item("main"))
let submenu = Menu.submenu([.item("a"), .item("b")])
Sign up to request clarification or add additional context in comments.

1 Comment

I'll define 2 enums like you are suggesting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.