[swift] 프로토콜과 프로토콜 어소시에이티드 타입 (Associated Types)의 제한사항

Swift에서 프로토콜은 관련된 메서드, 프로퍼티, 이니셜라이저 등을 그룹화하는 데 사용됩니다. 프로토콜을 정의할 때 associated types를 사용하면 해당 타입이 프로토콜의 요구사항을 충족시킬 수 있도록 합니다. 그러나 프로토콜과 associated types를 사용할 때 제한사항이 존재합니다.

Associated Types를 가진 프로토콜을 사용할 때의 제한사항

Associated Types를 가진 프로토콜을 사용할 때 몇 가지 제한사항을 고려해야 합니다.

1. 여러 associated types와 Generic의 결합

protocol SomeProtocol {
    associatedtype Item
    associatedtype AssociatedItem
    
    func doSomething(item: Item) -> AssociatedItem
}

위의 경우, associated type ItemAssociatedItem이 모두 사용되었습니다. 이 경우 제네릭을 사용하는 경우엔 동일한 associated type 이름에서 충돌이 발생합니다.

2. 프로토콜과 상속

associated type이 선언된 프로토콜에 상속을 사용할 때 associated type이 충돌할 수 있습니다.

protocol AnotherProtocol {
    associatedtype AnotherItem
}

protocol SomeProtocol: AnotherProtocol {
    associatedtype AnotherItem
}

위의 경우 입장에서, SomeProtocol의 associated type과 AnotherProtocol의 associated type이 모두 AnotherItem이라고 지정되었습니다. 이와 같이 associated type이 상속된 프로토콜과 충돌할 때는 구분이 필요합니다.

결론

Associated type을 갖는 프로토콜은 매우 유용하지만 이를 사용할 때에는 다른 타입과 조합하는 경우에 주의해야 합니다. 이러한 제한사항을 고려하면서 프로토콜을 설계하고 사용하면 더 안정적인 코드를 작성할 수 있습니다.

참고 자료: Apple Developer Documentation - Protocol, Swift.org - Generics

// Example code
protocol SomeProtocol {
    associatedtype Item
    associatedtype AssociatedItem
    
    func doSomething(item: Item) -> AssociatedItem
}