[Swift] 리턴 타입만 다르고 패턴은 같을 때

RudinP·2025년 9월 1일
0

Study

목록 보기
350/363

JSON 파싱을 할 때, 만약 리턴 타입만 다르고 메소드의 패턴은 같다면 제네릭을 사용하면 된다.

  1. 제네릭 사용
  2. 제네릭을 호출할 때 타입을 명시하기
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 {
    	...
    }
}
profile
iOS 개발자가 되기 위한 스터디룸...

0개의 댓글