Search code examples
arraysswiftuitableviewindexingtableview

Swift error Thread 1: Fatal error: Index out of range Tableview


unfortunately my code no longer works. I have not changed anything in it. I have sorted the files, but I also moved the json file. I get every time in the line : return questions[questionCount].question.count the error Thread 1: Fatal error: Index out of range

I have tried many things, I have also redone my JSON conversion with no result

Please help me

import UIKit



class TableViewController3: UIViewController {
    
    
    @IBOutlet weak var progressBar: UIProgressView!
    
    
    @IBOutlet weak var antwortLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var nextQuestion: UIButton!
 
    
    var tappedButtonsTags = [Int]()
    var questions = [Questions]()
    var questionCount = 0
    var yesCounter = 0
    var noCounter = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        parseJson()
        tableView.rowHeight = 100
        tableView.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
        nextQuestion.isEnabled = false
    }
    
    
    func loadData() {
        // code to load data from network, and refresh the interface
        tableView.reloadData()
    }
    
    private func parseJson(){
        
        guard let path = Bundle.main.path(forResource: "Fragen_Funktional", ofType: "json") else {
            return
        }
        let url = URL(fileURLWithPath: path)
        
        
        
        do {
            let jsonData = try Data(contentsOf: url)
            questions = try JSONDecoder().decode([Questions].self, from: jsonData)
            return
        }
        catch {
            print("Error: \(error)")
        }
    }
    
    @IBAction func nextQuestionBtn_Tapped(_ sender: UIButton) {
        
        
        
        
       // let length = questions.count
       // print("This is the length of Questions \(length)")
        
        if questionCount == questions.count - 1 {
            print("stop")
            StructOperation.glovalVariable.yesC = yesCounter
            StructOperation.glovalVariable.noC = noCounter
            nextQuestion.setTitle("Formular Beenden", for: .normal)
            let controller = storyboard?.instantiateViewController(withIdentifier: "endscreen") as! UINavigationController
            controller.modalPresentationStyle = .fullScreen
            present(controller, animated: true, completion: nil)
       
           
            
        } else {
            questionCount += 1
            // Load the data
            self.loadData()
            nextQuestion.isEnabled = false
            var setProgress = questionCount
            let progressAmounts = [0, 0.08, 0.16, 0.24, 0.32, 0.40, 0.52, 0.60, 0.68, 0.77, 0.88, 0.99]

            if progressAmounts.indices.contains(questionCount) {
                progressBar.setProgress(Float(progressAmounts[questionCount]), animated: true)
            } else {
                progressBar.setProgress(1, animated: true)
            }
            
           
            print (setProgress)
            
            
            
             
            
            
            
        }
        
    }
    
 
    
    
}

extension TableViewController3 : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return questions[questionCount].question.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let text = questions[questionCount].question
        let cell = tableView.dequeueReusableCell(withIdentifier: "Fragen3", for: indexPath as IndexPath) as! TableViewCellQuestion_3
        
        cell.unterFragenLabel.text =  questions[questionCount].questionpoints[indexPath.row].description
        
        antwortLabel.text = text
        cell.button_Ja.tag = indexPath.row
        cell.delegate = self
        
        cell.button_Ja.isEnabled = true
        cell.button_nein.isEnabled = true
        
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        cell.actionBlockYes = {
               //Do whatever you want to do when the button is tapped here
                cell.button_Ja.isEnabled = false
                cell.button_nein.isEnabled = true
            }
        cell.actionBlockNo = {
               //Do whatever you want to do when the button is tapped here
                cell.button_nein.isEnabled = false
                cell.button_Ja.isEnabled = true
            }
        
        cell.backgroundColor = UIColor.white
        
        return cell
    }
    
   
    
  
    
}

extension TableViewController3: MyTableViewCellDelegate {
    func onClickYes(x: Int) {
        yesCounter += 1
        print(yesCounter)
        nextQuestion.isEnabled = true
        
    }
    
    func onClickNo(x: Int) {
        noCounter += 1
        print(noCounter)
        nextQuestion.isEnabled = true
    }
    
    
    
}

Solution

  • I found the Answer. I deleted every JSON File in the Project and closed all Tabs. After I opened XCode again, I transfered the JSON File Ive needed but changed the name on the file and in the code. It worked.