Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Repository pattern in Swift

naoty
April 20, 2016

Repository pattern in Swift

potatotips #28

naoty

April 20, 2016
Tweet

More Decks by naoty

Other Decks in Technology

Transcript

  1. JO4XJGU protocol RecipeRepository { func find(id: UInt) -> Recipe? func

    findAll(query: Query, sort: Sort) -> [Recipe] func save(recipes: [Recipe]) -> Recipe? func delete(recipes: [Recipe]) -> Recipe? }
  2. JO4XJGU class MemoryRecipeRepository: RecipeRepository { let recipes = [ Recipe(id:

    1, name: “…”), Recipe(id: 2, name: “…”), Recipe(id: 3, name: “…”), ] func find(id: UInt) -> Recipe? { recipes.filter { $0.id == id }.first } }
  3. 1SPNJTF protocol RecipeRepository { func find(id: UInt) -> Task<Void, Recipe,

    ErrorType> func findAll(query: Query, sort: Sort) -> Task<Void, [Recipe], ErrorType> func save(recipes: [Recipe]) -> Task<Void, Recipe, ErrorType> func delete(recipes: [Recipe]) -> Task<Void, Recipe, ErrorType> }
  4. OBPUZ"OZ2VFSZ let query = AnyQuery.Equal(key: “name”, value: “naoty”) query.predicate //=>

    NSPredicate(format: "name == ‘naoty’") query.dictionary //=> ["name": “naoty”] let sort = AnySort.Ascending(key: “id”) sort.sortDescriptors //=> [NSSortDescriptor(key: "id", ascending: true)] sort.dictionary //=> ["sort": ["id"]]
  5. OBPUZ"OZ2VFSZ protocol RecipeRepository { func find(id: UInt) -> Task<Void, Recipe,

    ErrorType> func findAll(query: AnyQuery, sort: AnySort) -> Task<Void, [Recipe], ErrorType> func save(recipes: [Recipe]) -> Task<Void, Recipe, ErrorType> func delete(recipes: [Recipe]) -> Task<Void, Recipe, ErrorType> }
  6. ͜Ε͸Ͱ͖ͳ͍ protocol Repository { associatedtype Domain func find(id: Uint) ->

    Task<Void, Domain, ErrorType> } let repository: Repository = MemoryRecipeRepository()
  7. ܕফڈ struct AnyRepository<DomainType>: Repository { let _find: (id: UInt) ->

    Task<Void, DomainType, ErrorType> init<T: Repository where T.Domain == DomainType>(_ repository: T) { _find = repository.find } func find(id: UInt) -> Task<Void, DomainType, ErrorType> { return _find(id) } } let repository = AnyRepository(MemoryRecipeRepository()) // repository: AnyRepository<Recipe>