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()
}
}