Last active
March 10, 2024 21:56
-
-
Save Myrrel/a5d2fc6b5c6ce22f7f6735448707191f to your computer and use it in GitHub Desktop.
Endpoints with enum
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 | |
| // let charactersURL = ApiService.character.url | |
| //output: url = https://rickandmortyapi.com/api/character | |
| // let url = ApiService.characterPage(19).url | |
| // output: url = https://rickandmortyapi.com/api/character/?page=19 | |
| enum ApiService { | |
| private var baseURL: String { return "https://rickandmortyapi.com/api" } | |
| case character | |
| case characterPage(Int) | |
| case locations | |
| case episodes | |
| private var fullPath: String { | |
| var endpoint:String | |
| switch self { | |
| case .character: | |
| endpoint = "/character" | |
| case .characterPage(let id): | |
| endpoint = "/character/?page=\(id)" | |
| case .locations: | |
| endpoint = "/locations" | |
| case .episodes: | |
| endpoint = "/episodes" | |
| } | |
| return baseURL + endpoint | |
| } | |
| var url: URL { | |
| guard let url = URL(string: fullPath) else { | |
| preconditionFailure("The url used in \(ApiService.self) is not valid") | |
| } | |
| return url | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment