harshm31
harshm31

Reputation: 39

how to create an array of a struct having a property belonging to another struct

i have two structs "Meal" and "Food" i want to create an array of arrays

so these are my structs

struct Meal
{
   var name : String;
   var food : [Food];
}

struct Food
{
   var name :String;
   var description : String;
}

this is the code that im writing to creating the array :

var meals :[Meal] = [
        Meal(name:"breakfast",food : [(name:"pancakes",description:"bk1"),(name:"waffles",description:"bk2")]),
        Meal(name:"lunch",food : [(name:"pasta",description:"lunch1"),(name:"pizza",description:"lunch2")]),
        Meal(name:"dinner",food : [(name:"rice",description:"din1"),(name:"noodles",description:"din2")]),
    ];

but it gives an error : "Cannot convert value of type '(name: String, description: String)' to expected element type 'Food' " .

how do i fix this?

Upvotes: 1

Views: 65

Answers (1)

rmaddy
rmaddy

Reputation: 318804

Think about the syntax you are using to create a Food instance. Think about how you would create just one normally.

let someFood = Food(name: "pancakes", description: "bk1")

Use the same syntax in the array.

Meal(name: "breakfast", food: [Food(name: "pancakes", description: "bk1"), Food(name: "waffles", description: "bk2")]),

Upvotes: 1

Related Questions