Skip to content

Instantly share code, notes, and snippets.

@mokagio
Created May 18, 2018 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokagio/56a67b2285b2ddf5f3511cfb077cd415 to your computer and use it in GitHub Desktop.
Save mokagio/56a67b2285b2ddf5f3511cfb077cd415 to your computer and use it in GitHub Desktop.
Ready made `UITableViewDataSource` for those simple scenarios in which you want to display homogeneous data, of type `T`, in a single section, on a standard `UITableViewCell`
// swift version 4.1
import UIKit
/// Ready made `UITableViewDataSource` for those simple scenarios in which you want to display
/// homogeneous data, of type `T`, in a single section, on a standard `UITableViewCell`.
class SimpleDataSource<T>: NSObject, UITableViewDataSource {
typealias Item = T
let data: [T]
let configure: (UITableViewCell, T) -> UITableViewCell
let identifier = "simple-data-source-cell"
init(tableView: UITableView, data: [T], configure: @escaping (UITableViewCell, T) -> UITableViewCell) {
self.data = data
self.configure = configure
super.init()
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier)
}
func item(for indexPath: IndexPath) -> T? {
guard indexPath.row < data.count else { return .none }
return data[indexPath.row]
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
guard let item = item(for: indexPath) else { return cell }
return configure(cell, item)
}
}
@mokagio
Copy link
Author

mokagio commented May 18, 2018

My app has outgrown this very simple component, but I thought it'd be useful to dump it here for future use. I mean... is not rocket science, but will save some typing 😉 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment