Skip to content

Instantly share code, notes, and snippets.

@stinger
Created April 3, 2018 20:40
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 stinger/8632f0a6b95477d1c9912fab5c3eae0d to your computer and use it in GitHub Desktop.
Save stinger/8632f0a6b95477d1c9912fab5c3eae0d to your computer and use it in GitHub Desktop.
Data loading using protocols
import UIKit
import PlaygroundSupport
enum CoreError: Error, LocalizedError {
case unknown
var errorDescription: String? {
switch self {
case .unknown:
return "Unknown error occured"
}
}
}
enum ViewState<Content> {
case loading
case loaded(data: Content)
case failure(error: Error)
}
class LoadingView: UIView {}
class ErrorView: UIView {
func show(error: Error) {
// show the error
print("Got error: \(error.localizedDescription)")
}
}
protocol DataLoading {
associatedtype Data
var state: ViewState<Data> { get set }
var loadingView: LoadingView { get }
var errorView: ErrorView { get }
func update()
}
extension DataLoading where Self: UIView {
func update() {
switch state {
case .loading:
loadingView.isHidden = false
errorView.isHidden = true
case .failure(let error):
loadingView.isHidden = true
errorView.isHidden = false
errorView.show(error: error)
case .loaded(_):
loadingView.isHidden = true
errorView.isHidden = true
}
}
}
class SimpleView: UIView, DataLoading {
let loadingView: LoadingView = LoadingView()
let errorView: ErrorView = ErrorView()
var state: ViewState<String> = .loading {
didSet {
update()
guard case .loaded(let data) = state else { return }
print(data)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let view = SimpleView(frame: .zero)
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = view
view.state = .loaded(data: "Data loaded!")
view.state = .failure(error: CoreError.unknown)
PlaygroundPage.current.finishExecution()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment