New to swift and swift data so this might be an easy problem. I've tried searching the question already and might not be phrasing it correctly.
I have 2 data models. A list of accounts and a list of positions. There is a one to many relationship between accounts to positions. When I try to add a position to an account, my NewPositionView form is stuck in its init. When I put some simple debug in, it appears to be in an infinite loop in the init.
I put debug in to see why my NewPositionView wasn't opening and it appeared to be stuck in an infinite loop. All the positions for an account are listed on a PositionView.
import SwiftUI
import SwiftData
struct PositionView: View {
@Bindable var account: Accounts
@Environment(\.modelContext) var modelContext
@Query private var positions: [Positions]
init(account: Accounts){
self.account = account
let id = account.name
let predicate = #Predicate<Positions> { positions in
positions.inaccount?.name == id
}
_positions = Query(filter: predicate)
}
var body: some View {
VStack{
HStack {
Text("Account: \(account.name)")
.font(.title)
.fontDesign(.rounded)
.padding(.horizontal, 15)
.frame(minWidth: 75, maxWidth: .infinity, alignment: .leading)
Text("Current Value: \(account.displayTotalValue)")
.font(.title)
.fontDesign(.rounded)
.frame(minWidth: 75, maxWidth: .infinity, alignment: .leading)
}
HStack{
Text("Positions:")
}
if positions.count == 0 {
Text("No Positions for this account exist.")
.padding(15)
} else {
List{
ForEach(positions.indices, id:\.self){index in
VStack(alignment: .leading){
HStack{
Text("Test")
}
}
}.onDelete(perform: deletePosition)
}
}
}.toolbar{
NavigationLink("Add Position", destination: NewPositionView(inaccount: account))
}
}
private func deletePosition(indexSet: IndexSet){
for index in indexSet{
let position = positions[index]
modelContext.delete(position)
}
}
}
The newpostionView is here:
import SwiftUI
import SwiftData
struct NewPositionView: View {
@Bindable private var newPositionForm: NewPositionForm
@Bindable var inaccount: Accounts
@Environment(\.modelContext) private var modelContext
@Environment(\.dismiss) var dismiss
init(inaccount: Accounts){
let viewModel = NewPositionForm()
self.inaccount = inaccount
newPositionForm = viewModel
}
var body: some View {
Form{
VStack{
HStack{
FormTextField(label: "Position Stock Symbol", value: $newPositionForm.stockSymbol)
.padding(.horizontal, 10)
DatePicker(selection: $newPositionForm.dateOpened, in: ...Date.now, displayedComponents: .date) { Text("Position Open Date")
}
}
Button("Save Position"){
let position = Positions(stockSymbol: newPositionForm.stockSymbol, dateOpened: newPositionForm.dateOpened, inaccount: inaccount, currentValue: 0, goalValue: 0, activePosition: true)
modelContext.insert(position)
}
}
}
}
}
Thank you for all the help.