Skip to content

Instantly share code, notes, and snippets.

@nickoneill
Last active March 30, 2023 22:03
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nickoneill/f9aa63a5563bec81ac13c384b58a0df1 to your computer and use it in GitHub Desktop.
Save nickoneill/f9aa63a5563bec81ac13c384b58a0df1 to your computer and use it in GitHub Desktop.
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