typealias
키워드를 associatedtype
으로 대체하여 연관 타입 선언하기현재 typealias
키워드는 두 가지 타입을 선언하는 데 사용된다:
이 두 가지 선언은 서로 다르며, 별도의 키워드를 사용해야 한다. 이렇게 하면 둘의 차이를 명확히 강조할 수 있고, 연관 타입 사용에 대한 혼란을 줄일 수 있다.
제안하는 새로운 키워드는 associatedtype
이다.
프로토콜에서 typealias
를 연관 타입 선언에 재사용하는 것은 여러 면에서 혼란을 초래한다.
typealias
가 다른 곳에서와는 다른 의미를 가진다는 점이 명확하지 않다.특히, 2 + 3의 경우 프로그래머가 다음과 같은 코드를 작성할 수 있다.
protocol Prot {
typealias Container : SequenceType
typealias Element = Container.Generator.Element
}
이때 Element
가 Container.Generator.Element
에 대한 타입 별칭이 아니라, Container.Generator.Element
를 기본값으로 하는 새로운 연관 타입이라는 사실을 깨닫지 못할 수 있다.
반면, 아래 코드는
protocol Prot {
typealias Container : SequenceType
}
extension Prot {
typealias Element = Container.Generator.Element
}
Element
를 Container.Generator.Element
에 대한 타입 별칭으로 선언한다.
이러한 언어적 세부 사항은 현재 주의 깊게 고려해야만 이해할 수 있다.
연관 타입을 선언할 때 typealias
키워드 대신 associatedtype
을 사용한다.
이 방법은 앞서 언급한 문제를 해결한다:
typealias
는 이제 타입 별칭 선언에만 사용할 수 있다.이 방법은 이전 코드 예제에서 보여준 혼란을 제거한다.
protocol Prot {
associatedtype Container : SequenceType
typealias Element = Container.Generator.Element // 오류: 프로토콜 내부에서 타입 별칭을 선언할 수 없음, 대신 프로토콜 확장을 사용하세요
}
protocol Prot {
associatedtype Container : SequenceType
}
extension Prot {
typealias Element = Container.Generator.Element
}
고려된 대체 키워드: type
, associated
, requiredtype
, placeholdertype
, …
연관 타입을 선언하기 위해, Swift 2.2에서 associatedtype
을 추가하고 typealias
를 더 이상 사용하지 않도록(deprecate) 하며, Swift 3에서는 typealias
를 완전히 제거하는 것을 제안한다.
associatedtype
으로의 전환은 단순히 하나의 키워드를 다른 키워드로 대체하는 것이기 때문에, 기존 코드를 손상시키지 않고도 쉽게 자동화할 수 있다.