Не успевают приходить данные в массив перед сортировкой

Не успевают приходить данные с сервера, перед тем, как элементы из массива allCars должны начать сортироваться по секциям. Как заставить работать функцию loadSections() после загрузки всех данных в массив allCars. Или где-то таблицу нужно обновлять, или что-то еще. Объясните, пожалуйста, с решением, что именно мы должны тут делать.

import UIKit

protocol CarNameViewContollerDelegate { func chooseAutoPressTheCell(_ car: ArrayAutoData) }

struct Sections { var title: String var cars: [ArrayAutoData] }

class CarNameViewController: BackgroundVC, UITableViewDelegate, UITableViewDataSource {

let dataCar = AutoManager()
var allCars: [ArrayAutoData] = []
var sections: [Sections] = []

@IBOutlet weak var tableView: UITableView!
var delegate: CarNameViewContollerDelegate?

override func viewDidLoad() {
    super.viewDidLoad()
        
    chooseData()
    loadSections()
   
    tableView.delegate = self
    tableView.dataSource = self
}

func chooseData() {
    self.dataCar.autoData { data in
        for car in data {
            var auto = ArrayAutoData(name: car.name, models: [])
            
            for model in car.models {
                let models = Model(name: model.name, yearFrom: model.yearFrom, yearTo: model.yearTo)
                auto.models.append(models)
            }
            self.allCars.append(auto)
        }
    }
}

func loadSections() {
    let sectionNames = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "R", "S", "T", "V", "X", "W", "Z"]
    
    for sectionName in sectionNames {
        var section = Sections(title: sectionName, cars: [])

        for car in allCars {
            if car.name.starts(with: sectionName) {
                section.cars.append(car)
            }
        }
        sections.append(section)
    }
}

func numberOfSections(in tableView: UITableView) -> Int {
    sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    sections[section].cars.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    sections[section].title
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.backgroundColor = UIColor.clear
    cell.textLabel?.textColor = .white
    cell.textLabel?.text = sections[indexPath.section].cars[indexPath.row].name
 
    return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let car = sections[indexPath.section].cars[indexPath.row]

    delegate?.chooseAutoPressTheCell(car)
    navigationController?.popViewController(animated: true)
}

}


Ответы (0 шт):