작은 앱 프로젝트

오직 필요한 기능만 제공하는 '작은 앱'을 디자인하고 개발합니다.

Swift 문법

[Swift 문법] Generics - Associated Types 💡✨

김경환 - 작은 앱 프로젝트 2024. 6. 23. 13:28

[Swift 문법] Generics - Associated Types (제네릭 - 연관 타입) 💡✨

 

 

[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

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/generics/#Associated-Types

 

Documentation

 

docs.swift.org