Instantly share code, notes, and snippets.

Embed
What would you like to do?
Easily add async state tracking to your UITableView data sources
protocol TableValuable {
associatedtype TableItem
static func loadingValue() -> TableItem
static func failedValue() -> TableItem
func value() -> TableItem
}
enum TableState<T: TableValuable> {
case Loading
case Failed
case Items([T])
var count: Int {
switch self {
case let .Items(items):
return items.count
default:
return 1
}
}
func value(row: Int) -> T.TableItem {
switch self {
case .Loading:
return T.loadingValue()
case .Failed:
return T.failedValue()
case let .Items(items):
let item = items[row]
return item.value()
}
}
}
// conforming to the TableValuable protocol
extension String: TableValuable {
typealias TableItem = String
static func failedValue() -> TableItem {
return "Failed..."
}
static func loadingValue() -> TableItem {
return "Loading..."
}
func value() -> TableItem {
return self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment