Home > Software engineering >  Index out of range when presenting JSON data in tableview
Index out of range when presenting JSON data in tableview

Time:01-15

I am having issue identifying and changing the color of tableview rows that contain the same name value in both [ListStruct] which contains the inital data for the tableview rows, and [HighlightStruct] which contains the name that need to be highlighted.

Initially I have the following JSON array populate my tableview:

private func fetchJSON() {
        guard let url = URL(string: "www.test.com")
            else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "test=test1".data(using: .utf8)
        URLSession.shared.dataTask(with: request) { data, _, error in
            guard let data = data else { return }
            do {
                self.structure = try JSONDecoder().decode([ListStruct].self,from:data)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }}catch {print(error)}}.resume()}


struct ListStruct: Codable {
    let id: String
    let wo: String
    let name: String
    let type: String
}

Then the same view controller has a second JSON array that is decoded below for highlighting:

func processJSON(_ json: String) {
    do{
        let mydata = Data(json.utf8)
        let decoded = try JSONDecoder().decode(Set<HighlightStruct>.self,from: mydata)
        print(decoded)
    } catch {
        print(error)
    }
}

struct HighlightStruct: Codable, Hashable {
    var id: Int
    var name: String
}

Applying Highlight

var mySet: Set<HighlightStruct> = []
var highlightedStructure = [HighlightStruct]()
var structure = [ListStruct]()


 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell
        
        let portfolio: ListStruct
        portfolio = structure[indexPath.row]
        
        let highlight: HighlightStruct
        highlight = highlightedStructure[indexPath.row]
        
        //Highlight those that match in both arrays
        if highlight.wo == portfolio.wo {
               cell.backgroundColor = .yellow
        }
        
    

Getting index out of range

CodePudding user response:

You are getting index out of range error because your arrays are empty or there is no index that exist in your arrays. Maybe you can check your service call, the arrays could not be filled properly.

CodePudding user response:

Make sure ur two list count is same size, or process data to one list. You need to handle exceptions when structure does not have same wo to compare.

struct ListStruct: Codable {
    let id: String
    let wo: String
    let name: String
    let type: String
    let hightlight:HighlightStruct!
}


func processJSON(_ json: String) {
    do{
        let mydata = Data(json.utf8)
        let decoded = try JSONDecoder().decode(Set<HighlightStruct>.self,from: mydata)
        print(decoded)
        for hl in decoded{
            var filter = structure.filter({$0.wo == hl.wo})
            filter.hightlight = hl
        }
    } catch {
        print(error)
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell
    
    let portfolio: ListStruct
    portfolio = structure[indexPath.row]
    
    //Highlight those that match in both arrays
    if portfolio.hightlight?.wo == portfolio.wo {
           cell.backgroundColor = .yellow
    }
  •  Tags:  
  • Related