-
[Swift] AssociatedType 추상클래스에서의 사용개발/Swift 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를 지정해주면
각각 구체화될 클래스에서
각각에 맞게 타입을 사용할수있다.
'개발 > Swift' 카테고리의 다른 글
[Github action IOS] CI/CD Testflight 자동화 배포 하기 (0) 2022.05.19 [Github Action IOS] Pod install 할때 private repo(pod) 권한 관련 에러 (0) 2022.05.16 [Swift] Drag&Drop Interaction CustomValue 전달 (0) 2022.05.02 백준 1303 DFS 활용문제 (0) 2022.04.08 백준 1260 DFS 와 BFS 구현하기 (0) 2022.04.08