Fetch.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // Fetch.swift
  3. // Haneke
  4. //
  5. // Created by Hermes Pique on 9/28/14.
  6. // Copyright (c) 2014 Haneke. All rights reserved.
  7. //
  8. import Foundation
  9. enum FetchState<T> {
  10. case pending
  11. // Using Wrapper as a workaround for error 'unimplemented IR generation feature non-fixed multi-payload enum layout'
  12. // See: http://swiftradar.tumblr.com/post/88314603360/swift-fails-to-compile-enum-with-two-data-cases
  13. // See: http://owensd.io/2014/08/06/fixed-enum-layout.html
  14. case success(Wrapper<T>)
  15. case failure(Error?)
  16. }
  17. open class Fetch<T> {
  18. public typealias Succeeder = (T) -> ()
  19. public typealias Failer = (Error?) -> ()
  20. fileprivate var onSuccess : Succeeder?
  21. fileprivate var onFailure : Failer?
  22. fileprivate var state : FetchState<T> = FetchState.pending
  23. public init() {}
  24. @discardableResult open func onSuccess(_ onSuccess: @escaping Succeeder) -> Self {
  25. self.onSuccess = onSuccess
  26. switch self.state {
  27. case FetchState.success(let wrapper):
  28. onSuccess(wrapper.value)
  29. default:
  30. break
  31. }
  32. return self
  33. }
  34. @discardableResult open func onFailure(_ onFailure: @escaping Failer) -> Self {
  35. self.onFailure = onFailure
  36. switch self.state {
  37. case FetchState.failure(let error):
  38. onFailure(error)
  39. default:
  40. break
  41. }
  42. return self
  43. }
  44. func succeed(_ value: T) {
  45. self.state = FetchState.success(Wrapper(value))
  46. self.onSuccess?(value)
  47. }
  48. func fail(_ error: Error? = nil) {
  49. self.state = FetchState.failure(error)
  50. self.onFailure?(error)
  51. }
  52. var hasFailed : Bool {
  53. switch self.state {
  54. case FetchState.failure(_):
  55. return true
  56. default:
  57. return false
  58. }
  59. }
  60. var hasSucceeded : Bool {
  61. switch self.state {
  62. case FetchState.success(_):
  63. return true
  64. default:
  65. return false
  66. }
  67. }
  68. }
  69. open class Wrapper<T> {
  70. public let value: T
  71. public init(_ value: T) { self.value = value }
  72. }