Skip to content

Instantly share code, notes, and snippets.

@fmo91
Last active October 4, 2016 03:49
Show Gist options
  • Save fmo91/a8a0f06a90cad45bd7cce5c6bb072dfc to your computer and use it in GitHub Desktop.
Save fmo91/a8a0f06a90cad45bd7cce5c6bb072dfc to your computer and use it in GitHub Desktop.
Dequeuable.swift is a protocol extension that I heavily use in my projects to avoid using string literals while dequeuing cells from table views.
//
// Dequeuable.swift
//
// Created by Fernando Ortiz on 9/30/16.
// Copyright © 2016 Fernando Martín Ortiz. All rights reserved.
//
import UIKit
/**
Protocol extension used to easily dequeue UITableViewCells from UITableView
without using Strings (because they are too error-prone).
As an example:
let cell = ExampleTableViewCell.dequeue(from: tableView)
cell.configure(with: anObject)
return cell
This protocol does not require the UITableViewCell subclass implements any method,
but it is required to use xibs instead of directly embedding the cell in the storyboard,
and that the xib has the same name as the class.
*/
protocol Dequeable {}
extension Dequeable where Self:UITableViewCell {
static func dequeue(from tableView: UITableView) -> Self {
return tableView.dequeueReusableCell(withIdentifier: String(describing: Self.self)) as! Self
}
}
//
// ExampleTableViewCell.swift
//
// Created by Fernando Ortiz on 9/30/16.
// Copyright © 2016 Fernando Martín Ortiz. All rights reserved.
//
import UIKit
// So for example you can have something like this.
// Note that Dequeuable does not force ExampleTableViewCell
// to implement any method.
class ExampleTableViewCell: UITableViewCell, Dequeable {
// MARK: - Life cycle -
override func awakeFromNib() {
super.awakeFromNib()
}
// MARK: - Public configuration -
func configure(with anObject: AnObject) {
// Configures itself
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment