Avba
Avba

Reputation: 15276

how to define an array of a particular enum case in swift

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?

Upvotes: 0

Views: 311

Answers (1)

David Pasztor
David Pasztor

Reputation: 54745

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")])

Upvotes: 3

Related Questions