Segue using Diffable Data Sources

Code below in the `didSelectRowAt` function shows how we can retrieve an item and segue to a detail view controller.

import UIKit

struct Country: Hashable {
  let name: String
}

class DetailViewController: UIViewController {
  private var country: Country
  
  init(country: Country) {
    self.country = country
    super.init(nibName: nil, bundle: nil)
  }
  
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

class SampleViewController: UIViewController {
  private var dataSource: UICollectionViewDiffableDataSource<Int, Country>!
  private var tableView: UITableView!
  
  override func viewDidLoad() {
    super.viewDidLoad()
  }
}

extension SampleViewController: UITableViewDelegate {
  // segue to detail view controller
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let country = dataSource.itemIdentifier(for: indexPath) else {
      return
    }
    let detailVC = DetailViewController(country: country)
    navigationController?.pushViewController(detailVC, animated: true)
  }
}

Leave a comment