Skip to content

Instantly share code, notes, and snippets.

@yashthaker7
Last active July 6, 2018 05:57
Show Gist options
  • Save yashthaker7/4aafe5881a31db9e4547a50fa67c5218 to your computer and use it in GitHub Desktop.
Save yashthaker7/4aafe5881a31db9e4547a50fa67c5218 to your computer and use it in GitHub Desktop.
Generic TableView Controller
// GenericTableViewController.swift
// Generics
//
// Created by Yash Thaker on 01/07/18.
// Copyright © 2018 YashThaker. All rights reserved.
import UIKit
/*
// <---------- HERE IS HOW TO USE. ---------->
struct User {
let name, email: String
}
class UserCell: GenericCell<User> {
override var item: User! {
didSet {
textLabel?.text = "\(item.name):- \(item.email)"
}
}
}
class ViewController: GenericTableViewController<UserCell, User> {
override func viewDidLoad() {
super.viewDidLoad()
items = [User(name: "Yash", email: "yashthaker7@gmail.com"),
User(name: "Sunny", email: "sunnythaker2210@gmail.com")]
}
}
*/
class GenericTableViewController<T: GenericCell<U>, U>: UITableViewController {
var items = [U]()
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(T.self, forCellReuseIdentifier: cellId)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! T
cell.item = items[indexPath.row]
return cell
}
}
class GenericCell<U>: UITableViewCell {
var item: U!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment