I'm trying to copy an object from an array, into another array. I've attempted using append, but the array size remains at 0. I've also tried using insert, but that also is not working for me. I have been searching for several days, but haven't been able to find a solution. How can I successfully add the object to the array?
struct Test: View {
@Query private var issues: [Issue]
@Environment(\.modelContext) private var context
@State private var newIssue: Issue?
@State var hasIdentifedIssue = false
@State var identifiedIssues: [Issue]?
var body: some View {
NavigationStack {
List {
Section() {
Text("Hello")
}
}
.onAppear {
for number in 0...issues.count {
if issues[number].status == IssueStatus.Identified {
identifiedIssues!.append(issues[number])
}
}
}
}
}
}
Edit: I the issue is with the append (I commented out the following):
.onAppear {
// for number in 0...issues.count - 1 {
// if issues[number].status == IssueStatus.Identified {
print("in here")
print(issues.count) // prints 1
identifiedIssues!.append(issues[0])
// }
// }
}
Your code crash because of 0...issues.count
.
Array indices start at 0
up until issues.count - 1
, that is
0..<issues.count
.
Try this instead, after testing for issues.isEmpty
:
declare
@State private var identifiedIssues: [Issue] = []
if !issues.isEmpty {
for number in 0..<issues.count { // <--- here
if issues[number].status == IssueStatus.identified {
identifiedIssues.append(issues[number])
}
}
}
Better to use this:
for number in issues.indices { // <--- here
if issues[number].status == IssueStatus.identified {
identifiedIssues.append(issues[number])
}
}