swiftindexingstructtableview

Finding indexes of the maximum value in a struct array


I have a simple struct that I group and insert into a tableview with the title of sections and cell. I would like to get the indexes from the data for IndexPath(row: , section: ), which I then want to use for tableView.scrollToRow.

import UIKit

class ViewController: UIViewController {
    
   
    var sorted_data = Array<(key: String, value: Array<structdata>)>()
    
    struct structdata {
        
        var id: Int
        var row: String
        var section: String
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let someArray : [structdata] = [
            structdata(id: 1, row: "hello1", section: "monday"),
            structdata(id: 2, row: "hello2", section: "friday"),
            structdata(id: 3, row: "hello3", section: "monday"),
            structdata(id: 4, row: "hello4", section: "friday")
           ]
        
       
        
        let grouped = Dictionary(grouping: someArray, by: { $0.section })
        
        sorted_data = grouped.sorted { $0.key.localizedStandardCompare($1.key) == .orderedDescending }
      
        print(sorted_data)
        tableView.reloadData()
    }

func numberOfSections(in tableView: UITableView) -> Int {
        
        return sorted_data.count
        
   }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sorted_data[section].value.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
     
                    
                return "\(sorted_data[section].key)" 
        
     }
      
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            let ppp = sorted_data[indexPath.section].value[indexPath.row]
            cell.textLabel?.text = ppp.row
            
            return cell
    }

}

How to get the section and row index from the sorted_data that has the highest id? = id:4


Solution

  • The question is a bit unclear and I don't know what the exact end result is so this answer is a bit of a guess. But my guess is you want to find the indices in the array sorted_data.

    First to find the object with the max id value you can do

    someArray.max(by: { $0.id < $1.id })
    

    and then we can use the id and section properties from that object to find the first index matching the section and row

    Something like this

    if let maxObject = someArray.max(by: { $0.id < $1.id }) {
    
        let sectionIndex = sorted_data.firstIndex(where: { $0.key == maxObject.section })!
        let rowIndex = sorted_data[sectionIndex].value.firstIndex(where: { $0.id == maxObject.id })
    
        print(sectionIndex, rowIndex)
    }