Last active
March 30, 2023 22:03
-
-
Save nickoneill/f9aa63a5563bec81ac13c384b58a0df1 to your computer and use it in GitHub Desktop.
Easily add async state tracking to your UITableView data sources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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