개발/Swift
[Swift] AssociatedType 추상클래스에서의 사용
덤벨로퍼
2022. 5. 5. 18:47
protocol AbstractRepository{
func create(model :Model) -> Model
}
추상화된 리포지토리를 protocol로 구현했다.
이렇게 추상화된 리포지토리를 사용하면
구체화될 리포지토리에서 함수를 상속받아 구현 할수있다.
그러나 만약 Model이 구체화될 리포지토리마다 다르다면 어떻까
class UserRepository{
func create(model :User) -> User {}
}
class ProductRepository{
func create(model :Product) -> Product {}
}
이때 우리는 associatedType을 사용한다.
protocol AbstractRepository{
associatedtype Model : Domain
func create(model :Model) -> Model
}
class User:Domain {}
class Product: Domain {}
class UserRepository: AbstractRepository{
typealias Model = User
func create(model:User) -> User {
}
}
추상클래스 (AbstractRepository)에서 associatedType 을 사용하고
구현 클래스 (UserRepository)에서 typealias를 지정해주면
각각 구체화될 클래스에서
각각에 맞게 타입을 사용할수있다.