Skip to content

Instantly share code, notes, and snippets.

@piyushdec
Last active July 31, 2019 22:12
Show Gist options
  • Save piyushdec/7cc896b7789dee152f53f15e017cd908 to your computer and use it in GitHub Desktop.
Save piyushdec/7cc896b7789dee152f53f15e017cd908 to your computer and use it in GitHub Desktop.
import UIKit
typealias UserDataSource = UITableViewDiffableDataSource<UsersViewController.Section, User>
typealias UserSnapshot = NSDiffableDataSourceSnapshot<UsersViewController.Section, User>
class UsersViewController: UITableViewController {
var users = [User]()
var datasource: UserDataSource!
func configureDataSource() {
datasource = UserDataSource(tableView: tableView) { (tableview, indexpath, user)
-> UITableViewCell
let cell = tableView.dequeuReusableCell(withIdentifier: "identifier", for: indexpath )
cell.textLabel.text = user.name
return cell
}
}
func addNewUser(id: Int, name: String) {
users.append(User(id: 1, name: "Steve"))
createSnapshot(users)
}
func createSnapshot(_ users: [User]) {
let snapshot = UserSnapshot()
snapshot.appendSections([.main])
snapshot.appendItems(users)
datasource.apply(snapshot, animatingDifference: true)
}
}
extension UsersViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//based on your datasource (hashable) diffable will be able to lookup user using indexpath.
guard let user = datasource.itemIdentifier(for: indexPath) else {
return
}
print(user.name)
}
}
extension UsersViewController {
fileprivate enum Section {
case main
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment