I'm trying to understand SwiftUI and have a simple app in mind to help me learn. My app has one model and two views:
Model:
struct Tournament { // eventually will have more properties, such as Bool, Date, arrays, etc.
var name: String
var location: String = "Franchises"
#if DEBUG
var tournamentData = [
Tournament(name: "Season Opener"),
Tournament(name: "May Day Tournament"),
Tournament(name: "Memorial Day Tournament"),
Tournament(name: "School's Out Tournament")
]
#endif
}
ListView:
struct TournamentListView: View {
// should I use a different property wrapper if this is going to be something I refer to throughout the app?
@State var tournaments = tournamentData
var body: some View {
NavigationView {
VStack {
List(tournaments, id: \.name) { tournament in
NavigationLink(
destination: TournamentDetailView(tournaments: $tournaments, tournament: tournament),
label: { Text (tournament.name)}
)
}
Spacer()
NavigationLink(
destination: TournamentDetailView(tournaments: $tournaments, addingNewTournament: true),
label: { Text ("Add a new tournament") }
)
}.navigationTitle("Tournaments")
}
}
}
DetailView:
struct TournamentDetailView: View {
@Environment(\.presentationMode) var presentationMode
@Binding var tournaments: [Tournament]
@State var tournament = Tournament(name: "")
var addingNewTournament: Bool = false
var body: some View {
Form {
Section(header: Text("Tournament Info")) {
TextField("Name", text: $tournament.name)
TextField("Location", text: $tournament.location)
}
Section {
Button(action: {
if addingNewTournament { tournaments.append(tournament) }
else { /* what should I do here? */ }
presentationMode.wrappedValue.dismiss()
}) { Text(addingNewTournament ? "Create Tournament" : "Update Tournament") }
}
}
}
}
This example app is about 95% of the way there. Upon launch, I see the list of Tournaments and the "Add" link. If I click on "Add", I can see the Form, I can fill it out, press the "Create Tournament" and the item is saved to the array. If I press on an item already in the list, the only that doesn't work is that the changes aren't saved.
So I have two questions: one specific, one open-ended:
- How do I save modifications to an existing item?
- Am I doing this more-or-less the right way, or am I really swimming against the current? Are there any improvements I should/could make?
I recognize that there is no persistence, but that will come later.
Thanks for your help.