Last active
June 1, 2020 16:01
-
-
Save tanabe1478/ce9ae75f18ae53e95020c0bc64dfe1a9 to your computer and use it in GitHub Desktop.
Protocolではなく Genericsをつかったモジュール群の抽象化
This file contains hidden or 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
| import Foundation | |
| class BoardGameService<A: API, P: BoardGameParseable> { | |
| init(api: A, parser: P) { | |
| self.api = api | |
| self.parser = parser | |
| } | |
| let api: A | |
| let parser: P | |
| func boardGame(id: UInt) -> BoardGameEntity? { | |
| let json = api.json("/board-games/\(id)") | |
| return parser.parse(json) | |
| } | |
| } | |
| protocol API { | |
| func json(_ apiPathString: String) -> Data? | |
| } | |
| protocol Parser { | |
| associatedtype ResponseEntity: Codable | |
| func parse(_ obj: Codable) -> ResponseEntity | |
| } | |
| struct BoardGameAPI: API { | |
| func json(_ apiPathString: String) -> Data? { | |
| return """ | |
| {"id": 0} | |
| """.data(using: .utf8) | |
| } | |
| } | |
| protocol BoardGameParseable: Parser { | |
| func parse(_ obj: Codable) -> BoardGameEntity | |
| } | |
| struct BoardGameParser: BoardGameParseable { | |
| typealias ResponseEntity = BoardGameEntity | |
| func parse(_ obj: Codable) -> ResponseEntity { | |
| return BoardGameEntity(id: 0) | |
| } | |
| } | |
| struct BoardGameEntity: Codable, Equatable { | |
| var id: Int | |
| } | |
| let service = BoardGameService(api: BoardGameAPI(), parser: BoardGameParser()) | |
| let boardGame = service.boardGame(id: 0) | |
| print(boardGame!.id) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
きっかけ
BoardGameServiceとか各protocol名は引用してる記事から取ってきたやつ
https://twitter.com/t__nabe/status/1251522424580960256