JSON 파싱을 할 때, 만약 리턴 타입만 다르고 메소드의 패턴은 같다면 제네릭을 사용하면 된다.
enum ApiType: String {
case A
case B
}
private func fetch<ParsingType: Codable>(type: ApiType) async throws -> ParsingType {
var components = URLComponents(string: "https://어쩌구.com/\(type.rawValue)")
guard let url = components?.url else {
throw ApiError.invalidUrl(components?.host ?? "")
}
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse else {
throw ApiError.invalidResponse
}
guard httpResponse.statusCode == 200 else {
throw ApiError.failed(httpResponse.statusCode)
}
let decoder = JSONDecoder()
let result = try decoder.decode(ParsingType.self, from: data)
return result
}
~~
//사용하는 부분
func fetch() async {
do {
let aaa: A = try await fetch(type: .A)
} catch {
...
}
}