[Question] 아래 프로토콜(protocol)에서 fetchData() 함수의 반환 타입 [String]을 String 외의 다른 타입도 쓸 수 있도록 해 프로토콜의 재사용성을 높이는 방법은?
protocol DataFetchable {
func fetchData() async throws -> [String]
}
[Answer] 아래 코드처럼 Swift 제네릭(Generics)의 연관 타입(Associated Types)을 활용한다. 이렇게 하면 구체적인 타입을 나중에 지정할 수 있게 돼, 다양한 상황에 맞게 재사용할 수 있는 유연성이 생긴다.
protocol DataFetchable {
associatedtype FetchedDataType
func fetchData() async throws -> [FetchedDataType]
}
final class Fetcher: DataFetchable {
typealias FetchedDataType = SomeType
func fetchData() async throws -> [SomeType] {
// some code
}
}
참고 자료
Swift Language 공식 문서 - Generics - Associated Types
Documentation
docs.swift.org