iosswiftuikittableview

I cannot pass data from one View Controller to another


Could you help me with my code? I cannot pass my data on prepare segue. I cannot assign value of type Response to type Meals. I don't know what I did wrong. I just need a help with line prepare for segue. It is a last line of code. Will be glad for any help.

struct Response: Codable {
    var meals: [Meals]?
}

    struct Meals: Codable {
    var strMeal: String?
    var strMealThumb: String?
    var idMeal: String?
}

    class MealsViewController: UIViewController {
    
    //var results: Response?
   
    var meals : Meals = Meals()
    
    @IBOutlet weak var mealImage: UIImageView!
    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var idLbl: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        nameLbl.text = meals.strMeal
        idLbl.text = meals.idMeal
       
    }

    class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var resultsData: Response?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        
        getResultData {
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
         }
        
        tableView.delegate = self
        tableView.dataSource = self
        
    }
}
 

    extension ViewController: UITableViewDelegate, UITableViewDataSource {
        
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        resultsData?.meals?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
        let meal = resultsData?.meals
        cell.textLabel?.text = meal![indexPath.row].strMeal
        
        return cell
    }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            performSegue(withIdentifier: "showDetails", sender: self)
        }
        
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destination = segue.destination as? MealsViewController {
               destination.meals = resultsData // cannot assign value of type Response to type Meals
            }
        }

Please check it here.


Solution

  • Your meals should be outside the viewDidLoad

    It should be as below.

    class MealsViewController : UIViewController {
    
        var meals : Meals = Meals()
    
        override func viewDidLoad() {
             super.viewDidLoad()
    
             print("your meal name is==\(meals.strMeal ?? "")")
        }
    
    }