Build Simulator crash

hi there! i got this error when I try to use the simulator: Swift/ContiguousArrayBuffer.swift:600: Fatal error: Index out of range 2023-07-03 21:53:49.575166+0900 LRAT[72102:3459787] Swift/ContiguousArrayBuffer.swift:600: Fatal error: Index out of range

I've got this really long code and I really am unsure how to shorten it. but, when I try to use the simulator, I choose the pickers and it stops. sometimes it can choose choices in the pickers but when I try to export a pdf, it stops. just freezes. the choices are in a separate Swift file. I need help. The following is the code for this particular file(very incomplete).

import SwiftUI import UIKit import PDFKit struct NaturalSlopeFormView: View {

@Environment(\.presentationMode) var presentationMode

@State private var location: String = ""
@State private var evaluators: [String] = []
@State private var isDatePickerShown = false
@State private var selectedDate = Date()
@State private var slopeAnglePickerIndex = 0

//until the 31st variable @State private var unclearManagementPickerIndex = 0

@State private var relativeRiskPickerIndex1 = 0

//until #31 @State private var relativeRiskPickerIndex31 = 0

@State private var isFormSaved = false
@State private var isExportingPDF = false

@State private var evaluationsCountForCurrentDay = 0

var body: some View {

NavigationView { Form { Group { Section(header: Text("Date")) { DatePicker() {Text("Select a Date")}}

Section(header: Text("Location")) { TextField("Location", text: $location)}

Section(header: Text("Evaluators")) { ForEach(evaluators.indices, id: .self) { index in TextField("Evaluator (index + 1)", text: $evaluators[index])} Button(action: addEvaluator) { Label("Add Evaluator", systemImage: "plus.circle") } }

}

Group { Section(header: Text("Slope Angle").font(.title3).bold() ) { Picker("Criteria", selection: $slopeAnglePickerIndex, content: { ForEach(0..<QuestionData().slopeAngleChoices.count, id: .self) { index in Text(QuestionData().slopeAngleChoices[index])}}) .pickerStyle(MenuPickerStyle()) Picker("Relative Risk", selection: $relativeRiskPickerIndex1, content: { ForEach(0..<QuestionData().relativeRiskChoices.count, id: .self) { index in Text(QuestionData().relativeRiskChoices[index]) }}) .pickerStyle(MenuPickerStyle()) Text("Score: (QuestionData().slopeAngleScores[slopeAnglePickerIndex]), (QuestionData().relativeRiskScores[relativeRiskPickerIndex1])") } // Save Button Button(action: saveForm) { HStack { Spacer() Text("Save Form") Spacer() }} .disabled(isFormSaved) } .navigationBarItems(leading: HStack { Image("knu") // Replace "knulogo" with your actual image name .resizable() .aspectRatio(contentMode: .fit) .frame(height: 35) Text("Natural Slope Evaluation") .font(.title3) .bold() }, trailing: Button(action: exportToPDF) { Image(systemName: "square.and.arrow.up")})}}

func exportToPDF() {
    let pdfData = createPDF()
    
    let referenceNumber = generateReferenceNumber()
    let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(referenceNumber).pdf")

    do {
        try pdfData.write(to: fileURL)
        
        isExportingPDF = true
        
        let activityViewController = UIActivityViewController(
            activityItems: [fileURL],
            applicationActivities: nil
        )
        
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
           let mainWindow = windowScene.windows.first {
            mainWindow.rootViewController?.present(activityViewController, animated: true, completion: nil)}

isExportingPDF = false } catch {print("Failed to write PDF file: (error.localizedDescription)") } } func createPDF() -> Data { let pdfMetaData = [ kCGPDFContextCreator: "Natural Slope Evaluation App", kCGPDFContextAuthor: "Your Name", kCGPDFContextTitle: "Natural Slope Evaluation Form" ] let format = UIGraphicsPDFRendererFormat() format.documentInfo = pdfMetaData as [String: Any]

    let data = renderer.pdfData { (context) in
        context.beginPage()
        let titleFont = UIFont.systemFont(ofSize: 18.0, weight: .bold)
        let titleAttributes: [NSAttributedString.Key: Any] = [
            .font: titleFont]
        let textFont = UIFont.systemFont(ofSize: 12.0)
        let textAttributes: [NSAttributedString.Key: Any] = [
            .font: textFont]
        let photo = UIImage(named: "knu3")
        let photoRect = CGRect(x: 20, y: 20, width: 250, height: 80)

photo!.draw(in: photoRect) let titleText = NSAttributedString( string: "Natural Slope Evaluation Form", attributes: titleAttributes ) titleText.draw(at: CGPoint(x: 300, y: 20)) let referenceNumberText = NSAttributedString( string: "Reference Number: (generateReferenceNumber())", attributes: textAttributes) referenceNumberText.draw(at: CGPoint(x: 300, y: 50))

        let dateText = NSAttributedString(
            string: "Date: \(formattedDate())",
            attributes: textAttributes)
        dateText.draw(at: CGPoint(x: 300, y: 70))
        let locationText = NSAttributedString(
            string: "Location: \(location)",
            attributes: textAttributes)
        locationText.draw(at: CGPoint(x: 300, y: 90))
        
        let evaluatorsText = NSAttributedString(
            string: "Evaluators:\n\(formattedEvaluators())",
            attributes: textAttributes )
        evaluatorsText.draw(at: CGPoint(x: 300, y: 110))
        
        

        // Create a PDF document
        let pdf = PDFDocument()
        let page = PDFPage()
      //code

        var currentPosition = CGPoint(x: 20, y: 170)

        let relativeRiskOptions = ["A", "B", "C", "D", "E"]

        let tableData: [(String, Int, String)] = [
            ("Slope Angle", slopeAnglePickerIndex, relativeRiskOptions[relativeRiskPickerIndex1]),

//until #31st variable ]
} struct NaturalSlopeFormView_Previews: PreviewProvider { static var previews: some View { NaturalSlopeFormView() } }

Could you edit the code properly and format with Code formatter. In the present presentation it is just impossible to read. What are commented out lines ? What is the real code ? There seems to miss closing brackets… Where do you use relativeRiskPickerIndex31 ? Do you repeat code with relativeRiskPickerIndex1 to relativeRiskPickerIndex31 ? What are the values of those state var (they should always be between 0 and 4). Are they ? And please show where exactly the error occurs.

The code is very long so i hope this edit is sufficient to read. Where do you use relativeRiskPickerIndex31? - there are 31 "questions" in this part of the app,. each app has 2 sets of answers for users to choose from. #1 Slope Angle (they choose answer from picker one) and picker two in the relativeRiskPickerIndex.. basically there are from 1 until 31 risk picker indexes using this:

let relativeRiskChoices = ["Select", "Negligible", "Minor", "Moderate", "Significant", "Major"] let relativeRiskScores = ["-","A", "B", "C", "D", "E"] //the code above this line is from another swift file that just gets called to the file to the code below.

The state var values are all zero.

There is no error message inside the code lines but when I run the simulator and try to run and "pick" answers from the "questions" and answers inside the simulator, it Freezes and stops working. so i have to force quit it again to try to run it again.

however, if i do not use the pickers and just directly try to export pdf, it works.

The last time I tried this popped up on the debug area:

2023-07-03 22:28:42.363228+0900 LRAT[1382:14173] [Query] Error for queryMetaDataSync: 2 Swift/ContiguousArrayBuffer.swift:600: Fatal error: Index out of range 2023-07-03 22:32:08.544395+0900 LRAT[1382:12856] Swift/ContiguousArrayBuffer.swift:600: Fatal error: Index out of range (lldb)

I hope i shortened this code properly:

import SwiftUI import UIKit import PDFKit struct NaturalSlopeFormView: View { @Environment(.presentationMode) var presentationMode

//this part has 30 more state var of different names @State private var slopeAnglePickerIndex = 0

//this part has 1-31 @State private var relativeRiskPickerIndex1 = 0

var body: some View { NavigationView { Form { //this part has 7 groups with at most 5 sections each Group { Section(header: Text("Slope Angle").font(.title3).bold() ) { Picker("Criteria", selection: $slopeAnglePickerIndex, content: { ForEach(0..<QuestionData().slopeAngleChoices.count, id: .self) { index in Text(QuestionData().slopeAngleChoices[index]) } }) .pickerStyle(MenuPickerStyle()) Picker("Relative Risk", selection: $relativeRiskPickerIndex1, content: { ForEach(0..<QuestionData().relativeRiskChoices.count, id: .self) { index in Text(QuestionData().relativeRiskChoices[index]) } }) .pickerStyle(MenuPickerStyle())

                    Text("Score: \(QuestionData().slopeAngleScores[slopeAnglePickerIndex]), \(QuestionData().relativeRiskScores[relativeRiskPickerIndex1])")
                }

} .navigationBarItems(leading: HStack{ . . . } //this is for a button to export to PDF trailing: Button(action: exportToPDF){ . . . }

func addEvaluator() { . . . } func saveForm(){ . . . } func generateReferenceNumber() -> String{ . . . } func formattedDate() -> String { . . . } func formattedEvaluators() -> String{ . . . } func exportToPDF(){ . . . } func createPDF() -> Data{ . . . } let pdfMetaData = [ . . . ] //continuation for formatting of the pdf

let pdf = PDFDocument() let page = PDFPage() pdf.insert(page, at: 0)

        // Define the column widths
        let columnWidths: [CGFloat] = [400, 100, 100]

        // Define the row height and padding
        let rowHeight: CGFloat = 15
        let padding: CGFloat = 5

        // Define the starting position for drawing
        var currentPosition = CGPoint(x: 20, y: 170)


        // Define the data for the table
        let relativeRiskOptions = ["A", "B", "C", "D", "E"]
       
        // Define the data for the table
        let tableData: [(String, Int, String)] = [
            ("Slope Angle", slopeAnglePickerIndex, relativeRiskOptions[relativeRiskPickerIndex1]),
            ("Slope Height", slopeHeightPickerIndex, relativeRiskOptions[relativeRiskPickerIndex2]),
            ("Slope Aspect", slopeAspectPickerIndex, relativeRiskOptions[relativeRiskPickerIndex3]),
            ("Slope Elevation", slopeElevationPickerIndex, relativeRiskOptions[relativeRiskPickerIndex4]),
              //this part goes until relativeRiskPickerIndex31
            

for (index, rowData) in tableData.enumerated() { let column1Text = NSAttributedString(string: "(rowData.0)", attributes: textAttributes) let column2Text = NSAttributedString(string: "(rowData.1)", attributes: textAttributes) let column3Text = NSAttributedString(string: "(rowData.2)", attributes: textAttributes)

            let column1X = currentPosition.x
            let column2X = currentPosition.x + columnWidths[0]
            let column3X = currentPosition.x + columnWidths[0] + columnWidths[1]
            
            let column1Rect = CGRect(x: column1X, y: currentPosition.y, width: columnWidths[0], height: rowHeight)
            let column2Rect = CGRect(x: column2X, y: currentPosition.y + (rowHeight - column2Text.size().height) / 2, width: columnWidths[1], height: rowHeight)
            let column3Rect = CGRect(x: column3X, y: currentPosition.y + (rowHeight - column3Text.size().height) / 2, width: columnWidths[2], height: rowHeight)
            
            column1Text.draw(in: column1Rect)
            column2Text.draw(in: column2Rect)
            column3Text.draw(in: column3Rect)
            
            currentPosition.y += rowHeight + padding
       return data

} }

struct NaturalSlopeFormView_Previews: PreviewProvider { . . . } struct DatePickerSheet: View { . . . }

Thank you!

Hi, I was able to make it work. I decided to start from scratch.

instead of doing this:

        let tableData: [(String, Int, String)] = [
            ("Slope Angle", slopeAnglePickerIndex, relativeRiskOptions[relativeRiskPickerIndex1]),
            ("Slope Height", slopeHeightPickerIndex, relativeRiskOptions[relativeRiskPickerIndex2])

i did this instead:

        let tableData: [(String, String, String)] = [
            ("Slope Angle", QuestionData().slopeAngleChoices[slopeAnglePickerIndex], QuestionData().relativeRiskChoices[relativeRiskPickerIndex1]),
            ("Slope Height", QuestionData().slopeHeightChoices[slopeHeightPickerIndex], QuestionData().relativeRiskChoices[relativeRiskPickerIndex2]),
Build Simulator crash
 
 
Q