I went a little crazy on the ZooKeeper lesson and ran into an issue where I want to add a animal to a certain section in the list. How is this done? How to I append a new animal to say the “Critters” section? Would I use an enum instead of these nested arrays?
Button("Add") {
animalGroups.append(AnimalGroup(groupName: "Critters", animals: [(Animal(name: "Missing0"))]))
}
The code in question is above with the full code below.
import SwiftUI
struct ContentView: View {
@State var animalGroups = [
AnimalGroup(groupName: "Pets", animals: [
Animal(name: "Dog"),
Animal(name: "Cat"),
Animal(name: "Parrot"),
Animal(name: "Mouse")
]),
AnimalGroup(groupName: "Farm", animals: [
Animal(name: "Cow"),
Animal(name: "Horse"),
Animal(name: "Goat"),
Animal(name: "Sheep"),
]),
AnimalGroup(groupName: "Critters", animals: [
Animal(name: "Firefly"),
Animal(name: "Spider"),
Animal(name: "Ant"),
Animal(name: "Squirrel"),
])
]
var body: some View {
VStack{
Text("I 🍆 Lists").font(.headline)
List {
ForEach(animalGroups) {animalGroup in
Section(header: Text(animalGroup.groupName)) {
ForEach(animalGroup.animals) { animal in
Text(animal.name)
}
}
}
}
.listStyle(InsetGroupedListStyle())
Button("Add") {
animalGroups.append(AnimalGroup(groupName: "Critters", animals: [(Animal(name: "Missing0"))]))
}
Spacer()
}
}
}
struct Animal: Identifiable {
var id = UUID()
var name: String
}
struct AnimalGroup: Identifiable {
var id = UUID()
var groupName: String
var animals: [Animal]
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}