0

I am looking to (per this example) add more items to a specific section of a structured array after creating the initial entry.

struct Zoo {
    let section: String
    let items: [String]
}

var objects = [Zoo]()

let animals = Zoo(section: "Animals", items: ["Cat","Dog","Mouse"])
let birds = Zoo(section: "Birds", items: ["Crow","Pidgeon","Hawk"])

let reptiles = ["Snake","Lizard"]

objects.append(animals)
objects.append(birds)

// ... varous logic and proccessing where I determine I need 
// to add two more items to the animals section...

// trying to extend animals with two more entries.
// this is where I am getting hung up:
objects[0].items.append(reptiles)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
David
  • 171
  • 2
  • 11
  • use var instead of let https://stackoverflow.com/questions/24002092/what-is-the-difference-between-let-and-var-in-swift – Arti Mar 15 '18 at 18:30
  • changed the lets to vars but get the following form the last line where I try to append: Cannot convert value of type '[String]' to expected argument type 'String' – David Mar 15 '18 at 18:40

1 Answers1

0

Remove the following code

  objects[0].items.append(reptiles)

Use this code:

objects[0].items +=  reptiles

Update for Swift 5:

In Swift 5, this solution will not work and you will get an error like

"Left side of mutating operator isn't mutable: 'items' is a 'let' constant"

The solution is to change the structure :

struct Zoo {
    let section: String
    var items: [String]
}
Razib Mollick
  • 4,617
  • 2
  • 22
  • 20