Search code examples
jsonswiftrealmnsarray

Nesting arrays in Realm with Swift


I have read several examples on SO on how to store arrays of data to Realm. Still, I am not finding a particularly clear example.

In short, I have a (simplified) JSON as below which I would like to store in Realm. How can I add an array of ingredients to Realm, so that it is contained within an array of menuItems?

{
   "menuItems": [
      {
         "name": "name 1",
         "ingredients": ["ingredient 1", "ingredient 2"]
      },
      {
         "name": "name 2",
         "ingredients": ["ingredient 1", "ingredient 2", "ingredient 3"
         ]
      }
   ]
}

I have my realm models set up as such:

class MenuItemsRealm: Object {

    @objc dynamic var name: String = ""
    var ingredients = List<IngredientItemsRealm>()
}

class IngredientItemsRealm: Object {

    @objc dynamic var ingredientItem: String = ""
} 

Solution

  • In your JSON, you're stating that a menuItem object has a property/variable called ingredients and it contains an array of String. What you probably want to do is create a array of Objects that contains the specific ingredientItem property/variable.

    To exemplify your JSON would be something like this:

    {
       "menuItems": [
          {
             "name": "name 1",
             "ingredients": [
                 {
                     "ingredientItem": "item name"
                 }
             ]
          }
       ]
    }