Enum Factories And Generic Data Sources

Enum Factories And Generic Data Sources

Presented at CocoaHeads Montreal on November 16th, 2017.

732de78cba7ebf62ccb9cf3ea08d618b?s=128

Olivier Collet

November 16, 2017
Tweet

Transcript

  1. ENUM FACTORIES AND GENERIC DATA SOURCES OLIVIER COLLET. COCOAHEADS MONTREAL.

    16.11.2017
  2. PHOTOS, PHOTOS, MORE PHOTOS • SEARCH • NEW FEED •

    COLLECTION • PHOTOGRAPHER
  3. SAME THING DIFFERENT SOURCE

  4. IT STARTS WITH A PAGED REQUEST I’ll spare you the

    details. The most important thing is this: struct Cursor { let page: Int let perPage: Int let parameters: [String: Any]? }
  5. THEN SUBCLASSES • For each API endpoint that uses paging

    • For photos and collections
  6. LET’S MOVE TO THE STUFF THE DATA SOURCE • It

    uses generics to handle photos and collections • It uses a factory to generate cursors and requests protocol PagedDataSourceFactory { func initialCursor() -> Cursor func request(with cursor: Cursor) -> PagedRequest }
  7. SO WHAT ABOUT THE FACTORY? THAT’S WHERE IT GETS REALLY

    enum PhotosDataSourceFactory: PagedDataSourceFactory { case photos(order: GetPhotosRequest.Order) case trending case search(query: String) case collection(identifier: String, curated: Bool) }
  8. WHAT ABOUT THAT PROTOCOL? IT’S GETTING func initialCursor() -> PagedRequest.Cursor

    { switch self { case .photos(let order): return GetPhotosRequest.cursor(with: order, page: 1, perPage: 20) case .trending: return GetHomePhotosRequest.cursor(with: nil) case .search(let query): return SearchPhotosRequest.cursor(with: query, page: 1, perPage: 20) ... } func request(with cursor: PagedRequest.Cursor) -> PagedRequest { switch self { case .photos(let order): return GetPhotosRequest(orderBy: order, page: cursor.page, perPage: cursor.perPage) case .trending: return GetHomePhotosRequest(with: cursor) case .search(let query): return SearchPhotosRequest(with: query, page: cursor.page, perPage: cursor.perPage) ... }
  9. FACTORY BONUS IT CREATES THE DATA SOURCE var dataSource: PagedDataSource<Photo>

    { return PagedDataSource<Photo>(with: self) }
  10. OK, BUT HOW TO USE THIS? The PhotosViewController uses a

    data source: var dataSource: PagedDataSource<Photo> Which is set as easily as this: photosViewController.dataSource = PhotosDataSourceFactory.search(query:”summer").dataSource
  11. HOPE YOU ENJOYED QUESTIONS?

  12. Olivier Collet 1-man wolf pack building all the native apps

    at Unsplash @ocollet