Skip to content

Instantly share code, notes, and snippets.

@Myrrel
Last active March 10, 2024 21:56
Show Gist options
  • Save Myrrel/a5d2fc6b5c6ce22f7f6735448707191f to your computer and use it in GitHub Desktop.
Save Myrrel/a5d2fc6b5c6ce22f7f6735448707191f to your computer and use it in GitHub Desktop.
Endpoints with enum
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