Can I restrict an enum to certain cases of another

2019-04-21 13:36发布

问题:

Say I have a bakery and an inventory of ingredients:

enum Ingredient {
    case flower     = 1
    case sugar      = 2
    case yeast      = 3
    case eggs       = 4
    case milk       = 5
    case almonds    = 6
    case chocolate  = 7
    case salt       = 8
}

A case's rawValue represents the inventory number.

Then I have two recipes:

Chocolate Cake:

  • 500g flower
  • 300g sugar
  • 3 eggs
  • 200ml milk
  • 200g chocolate

Almond Cake:

  • 300g flower
  • 200g sugar
  • 20g yeast
  • 200g almonds
  • 5 eggs
  • 2g salt

Now I define a function

func bake(with ingredients: [Ingredient]) -> Cake

Of course I trust my employees, but I still want to make sure they only use the right ingredients to bake a cake.